簡體   English   中英

為什么屬性不能綁定到 function 本身

[英]Why can't a property be bound to function itself

我知道為了將屬性綁定到 function 您需要將其添加到其原型中。 例如:

 function Animal(name) { this.name = name; }; Animal.prototype.number = 20; Animal.prototype.bark = function() {console.log('Woof')}; let mike = new Animal('Mike'); console.log(mike.number) mike.bark();

也許這是一個非常幼稚的問題,但為什么不允許將屬性綁定到 function 本身? 例如,執行以下操作:

 function Animal(name) { this.name = name; }; Animal.bark = function() {console.log('Woof')}; Animal.number = 20; let mike = new Animal('Mike'); console.log(mike.number) mike.bark();

JavaScript 中的對象使用原型 inheritance。 每個 object 都繼承自其他一些 object 或null 這條鏈繼續 - 所有對象最終都繼承自null

If an object inherits from another, all of the properties available on the parent object will be available on the child object (unless the child object defines a property with the same name, effectively shadowing and hiding the name on the parent).

如果 Animal 的實例繼承自 Animal 本身,例如

function Animal(name) {
    this.name = name;
};

Animal.bark = function() {console.log('Woof')};
Animal.number = 20;

然后 Animal 的實例將從function Animal繼承,這是一個 function - 並且將是函數並且還將繼承.call.apply等等。 這幾乎不是開發人員想要的。

擁有一個實例繼承的單獨可控 object 更有意義,因此決定通過<functionName>.prototype使 object 可引用。

原型鏈為:

instance <- Animal.prototype <- Object.prototype

Animal <- Function.prototype <- Object.prototype

讓實例也繼承自Function.prototype和函數只是沒有意義。 人們幾乎總是希望普通對象作為實例,而不是可調用函數。

Animal.prototypeAnimal分開的另一個好處是,您可以同時擁有原型上的屬性和 function 或 class 本身的屬性,這是將實例值和方法與實用程序值和函數分開的好方法 - 它們是關聯的與 class,但不必特別與任何實例有關。

 function Animal(name) { this.name = name; }; Animal.prototype.bark = function() {console.log(this.name + ' says Woof')}; Animal.checkIsAnimal = function(possibleAnimal) { console.log('Is this an animal? ' + (possibleAnimal instanceof Animal)); }; const mike = new Animal('Mike'); Animal.checkIsAnimal({}); Animal.checkIsAnimal(mike);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM