以下两个声明有什么区别?
Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }
是否可以将第一条语句视为静态方法的声明,将第二条语句视为实例方法的声明?
最佳答案
是的,第一个函数与 constructor function 的对象实例没有关系,您可以将其视为'静态方法'。
在 JavaScript 中,函数是 first-class对象,这意味着您可以像对待任何对象一样对待它们,在这种情况下,您只需将属性添加到 函数对象。
第二个函数,当您扩展构造函数原型(prototype)时,它将可用于使用 new
创建的所有对象实例。关键字,并且该函数中的上下文(this
关键字)将引用您调用它的实际对象实例。
考虑这个例子:
// 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:Class.method 与 Class.prototype.method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1635116/