[英]What is the difference between members on prototype object and on constructor function?
My question is not about the difference between object's members and prototype members. 我的问题不是关于对象成员和原型成员之间的区别。 I understand that.
我明白那个。 I think it is similar like C# object members and static members on the class.
我认为这类似于C#对象成员和类中的静态成员。
My question is about difference between members on constructor function and on prototype object . 我的问题是关于构造函数和原型对象上的 成员之间的区别。 Comparing to C# they both are "static".
与C#相比,它们都是“静态”的。 So what is the difference?
那么区别是什么呢? I only observed, that prototype members can be called the same way on instances directly, or on Constructor.prototype.
我只观察到,可以直接在实例上或在Constructor.prototype上以相同的方式调用原型成员。 The constructor function members can be called only on constructor function.
只能在构造函数上调用构造函数成员。 When to use which approach?
什么时候使用哪种方法?
To illustrate this, imagine I need count of Persons. 为了说明这一点,假设我需要人数统计。
Example using constructor function members: 使用构造函数成员的示例:
function Person () {
Person.countOfCreatedPersons = (Person.countOfCreatedPersons || 0) + 1;
}
Person.Count = function () {
return Person.countOfCreatedPersons;
}
var p = new Person();
alert(Person.Count());
Example using prototype members: 使用原型成员的示例:
function Person () {
Person.prototype.countOfCreatedPersons = (Person.prototype.countOfCreatedPersons || 0) + 1;
}
Person.prototype = {
Count: function () {
return this.countOfCreatedPersons;
}
}
var p = new Person();
alert(Person.prototype.Count()); // or p.Count()
When you add a property to the prototype of an object, every object that inherits from that prototype has the property: 当向对象的原型添加属性时,从该原型继承的每个对象都具有该属性:
function Ob(){};
Ob.prototype.initialised = true;
var ob1 = new Ob();
alert(ob1.initialised); //true!
alert(Ob.initialised); //undefined;
If you add it to the constructor, is like a static property. 如果将其添加到构造函数中,就像一个静态属性。 Instances won't have acces to them.
实例将没有权限。
function Ob2(){};
Ob2.initialised = true;
var ob2 = new Ob2();
alert(ob2.initialised); //undefined
alert(Ob2.initialised); //true
Besides, if you add a method to the prototype, the this
variable inside the method will point to your object (the instance of the class you've created with new
). 此外,如果您向原型添加一个方法,则
this
方法内部的this
变量将指向您的对象(您使用new
创建的类的实例)。 This is not true for class methods : 对于类方法不是这样:
function Obj() {
this.value = 1;
}
Obj.prototype.getValue = function() {
return this.value;
};
Obj.getValue = function() {
return this.value;
};
var ob3 = new Obj();
alert(ob3.getValue()); //'1'!
alert(Obj.getValue()); //undefined!
Hope this explains. 希望这能解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.