Rob Wpostrational提出了一个问题:JavaScript: Class.method vs. Class.prototype.method,或许与您遇到的问题类似。
回答者CMS给出了该问题的处理方式:
Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.
In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.
The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new
keyword, and the context within that function (the this
keyword) will refer to the actual object instance where you call it.
Consider this example:
// constructor function function MyClass () { var privateVariable; // private member only available within the constructor fn this.privilegedMethod = function () { // it can access private members //.. }; } // A 'static method', it's just like a normal function // it has no relation with any 'MyClass' object instance MyClass.staticMethod = function () {}; MyClass.prototype.publicMethod = function () { // the 'this' keyword refers to the object instance // you can access only 'privileged' and 'public' members }; var myObj = new MyClass(); // new object instance myObj.publicMethod(); MyClass.staticMethod();
希望本文对你有帮助,欢迎支持JavaScript中文网