var now = new Date; alert(now.year); now.year = 2006; alert(now);
至于采用哪种形式主要取决于个人的编程风格,采用第一种形式结构紧凑,更容易理解。但是假如你想在对象定义以后再添加Getter或Setter,或者这个对象的原型不是你写的或是内置对象,那么只好采用第二种方式了。 下面是一个为Mozilla浏览器添加innerText属性的实现: 复制代码 代码如下: HTMLElement.prototype.__defineGetter__ ( "innerText",function() //define a getter method to get the value of innerText, //so you can read it now! { var textRange = this.ownerDocument.createRange(); //Using range to retrieve the content of the object textRange.selectNodeContents(this); //only get the content of the object node return textRange.toString(); // give innerText the value of the node content }