5

我想知道,JavaScript 中的原型方法和非原型方法有什么区别?任何帮助都深表感谢。

4

1 回答 1

10

A non-prototyped method will take up memory in every instance of the class.

It will also (assuming it's declared in the scope of the class constructor) have access to any other private variables (or methods) declared in that scope.

For example, this will create an instance of the function per object, and that function can access myVar:

function MyObject() {
     var myVar;
     this.func = function() { ... };
};

and in this case there's only one instance of the function shared between every instance of the object, but it will not have access to myVar:

function MyObject() {
     var myVar;
};

MyObject.prototype.func = function() { ... };
于 2012-05-22T15:19:25.710 回答