javascript set prototype with this.prototype

时间:2015-10-06 08:31:03

标签: javascript

If I want to set the prototype I need to do this always outside of the function/object. I want to do that with this.prototype...

example:

MyPrototype = function() {
    this.name = "MyPrototype";
    this.number = 3;
}
MyObjectToExtend = function() {
    this.prototype = new MyPrototype(); //<-- I want this
    this.name = "MyObjectToExtend";
}
o = new MyObjectToExtend();

If i want to get o.number i will get nothing. But it is possible to access it with o.prototype.numer but I don't think that this is how you should get it, because the bellow example is working fine...

MyPrototype = function() {
    this.name = "MyPrototype";
    this.number = 3;
}
MyObjectToExtend = function() {
    this.name = "MyObjectToExtend";
}
MyObjectToExtend.prototype = new MyPrototype(); //<-- I don't want this
o = new MyObjectToExtend();

Now i can access o.number and it will give me 3 as it should be.

But I don't want this, I want to set the prototype as in the top example...

1 个答案:

答案 0 :(得分:0)

在这种情况下,this关键字是对您的类实例的引用。有一个名为__proto__的属性允许您更改此特定实例的原型值,但不推荐使用它,并且在这种情况下它不会影响您的类的其他实例。

您可以使用Object.getPrototypeOf(this).number = 3向原型中添加属性,但如果不使用MyObjectToExtend.prototype = new MyPrototype();__proto__,则无法更改原型的值。