关于prototype

来源:互联网 发布:mouldflow软件 编辑:程序博客网 时间:2024/04/28 06:28
犀牛书9.2写道:
After creating the empty object, new sets the prototype of that object. The prototype of an object is the value of the prototype property of its constructor function. All functions have a prototype property that is automatically created and initialized when the function is defined. The initial value of the prototype property is an object with a single property. This property is named constructor and refers back to the constructor function with which the prototype is associated. This is why every object has a constructor property. Any properties you add to this prototype object will appear to be properties of objects initialized by the constructor.

每个function都有一个prototype属性。当和new操作符一起使用时,function就成为了构造函数,其prototype的所有属性都会自动复制到新创建的对象上,而且可以直接访问。比如:
Car.prototype.color = "red";var car1 = new Car();var car2 = new Car();

这样的话,car1和car2都会有一个color属性,而且值默认都是"red"。也由于这个原因,prototype通常用于定义公用的方法,而不是属性。

prototype对象至少都会有一个constructor属性,这个属性是反向关联到构造函数本身。(结合第1条,每个对象都可以直接访问这个constructor属性)

-------------------------------------分隔线------------------------------------

an object inherits properties even if they are added to its prototype after the object is created. This means that it is possible (though not necessarily a good idea) to add new methods to existing classes.

-------------------------------------分隔线------------------------------------

此外,以下代码说明了从prototype继承得到的属性与自有属性的区别
var r = new Rectangle(2, 3);r.hasOwnProperty("width");   // true: width is a direct property of rr.hasOwnProperty("area");    // false: area is an inherited property of r"area" in r;                 // true: "area" is a property of r

对象本身并没有prototype属性,是对象的构造函数才有,只是prototype的所有属性,都会被复制到对象上,从而可以直接访问而已,有点类似于Struts2中的值栈。

-------------------------------------分隔线------------------------------------

要注意,由于prototype自身也是一个对象,所以它也有一个构造函数。没有进行特殊处理的话,它的构造函数是Object()。
原创粉丝点击