在stackoverflow上看到一個這樣的提問,以下代碼有什麼差別?
Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }
看來确實有很多人和我一樣對這個問題有疑問,實際上這個牽涉到static和dynamic方法的概念。
Class.method這種模式定義的method是綁定在Class對象之上的。在js中,我們知道一切皆為對象,包括Class(本質上是一個function)。當我們以ClassFunction.method方式定一個一個method時就是在function對象上定義了一個屬性而已。這個Class.method和通過new Class()生成的instance沒有任何關系,我們可以認為這種Class.method形式為static method.
而第二種Class.prototype.method,我們實際上是在擴充構造函數的prototype功能,它将在通過new Class()生成的每一個object instance上面存在,而在這個instance.method中的this将指向實際調用的object.
看下面的代碼加深了解:
// 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();
注意:将公共的method放到constructorFunction.prototype中去供instance繼承,(好處是避免代碼的重複,因為如果放到constructorFunction中通過this.method=function(){}的方式去定義,雖然instance.method也可以通路,但是代碼是有copy的!!!)而資料則放到constructor function中去定義,這樣每一個instance的資料都是不同的!!
轉載于:https://www.cnblogs.com/kidsitcn/p/11161396.html