开发者

JavaScript - Trying to add a prototype from within a prototype

This sounds easier than it should be, but I'm having issues trying to resolve this. My situation is basically, I can create a class that's going to use prototype (example: function exClass() {}).

And if I want to add onto the class, I can just use: exClass.pro开发者_运维技巧totype.newMethod() = '';.

So why is it that if I'm in, for example, the prototype "newMethod", I can't add a new prototype to "exClass" anymore. An example of what I mean is: this.prototype.test_var1 = '' - it fails, as does exClass.test_var1.

Why am I unable to add more to the class from within one of its subclasses?


The prototype of an object is not a property called prototype on the object. The prototype field on a function is the object that will become the prototype of objects created with that function. An object can access the prototype of the function that created it through the constructor function. For example, this.constructor.prototype.test_var1 = '' would work in most cases.

I say in most cases because many JavaScript engines have a built in __proto__ that is the object's prototype and can be modified on the fly, but this is not supported in IE for example.

In ES5 you can use Object.getPrototypeOf() to get the prototype reliably. So for example, you can say, Object.getPrototypeOf(this).test_var1 = '' in ES5 which will work in modern browsers but not browsers without ES5 support.


The prototype property of the constructor function exClass does not refer to the same object as the prototype property of an instance of exClass, which is what this references inside newMethod. Proof:

function exClass() {}
exClass.prototype.newMethod = function() {
    console.log(this.prototype === exClass.prototype); // false
    console.log(this.prototype); // undefined
}

var obj = new exClass();
obj.newMethod();

Output:

false
undefined

More generally, every object in JavaScript has a prototype object. The prototype property of a function specifies what the prototype object will be for the class of objects created with that function.

Nothing prevents you from modifying a function's prototype from within another function:

exClass.prototype.newMethod = function() {
    exClass.prototype.anotherMethod = function() {}
}

Or more generically:

exClass.prototype.newMethod = function() {
    this.constructor.anotherMethod = function() {}
}

But I wouldn't recommend it.


You can't get at an object's parent prototype via this.prototype. You have to use this.constructor.prototype (although this will affect the behavior of all objects of that type, in this case exClass). This snippet will alert 'hello world'.

function exClass() {};

exClass.prototype.newMethod = function() {
    this.constructor.prototype.test_var1 = 'hello world';
}

obj = new exClass();
obj.newMethod();
alert(obj.test_var1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜