簡體   English   中英

為什么不能覆蓋類(函數)描述中的方法定義?

[英]Why can't I override the method definition in the class(function) description?

我不太了解,為什么在第一個日志消息Prototype: [object Object] ,而在第二條消息中卻是Prototype: New Plant

function Plant() {
this.toString = function() {
        return "Plant";
    }
}

function Fruit(name) {
    Plant.call(this);
    this.name = name;
    this.toString = function() {
        return "Fruit";
    }
}
Fruit.prototype = Object.create(Plant.prototype);     
var apple = new Fruit("apple");

console.log("Prototype: " + Object.getPrototypeOf(apple));
Plant.prototype.toString = function() {
    return "New Plant";
}
console.log("Prototype: " + Object.getPrototypeOf(apple));

我以為自從我在Plant類中定義toString()方法以來,所有Fruit實例也將具有此方法?

您所有的Fruit實例可以訪問Plant原型上的.toString()方法。 但是,該方法 Fruit構造函數中的直接賦值覆蓋 一旦Fruit構造函數為this.toString分配了某些this.toString ,它將始終在原型鏈中隱藏.toString()

請記住,在Fruit構造函數的代碼中, this是指新創建的實例。 因此, this屬性的分配就是將直接存在於每個實例上的屬性。

x.toString()類的任何表達式中,搜索名稱為“ toString”的屬性都是從對象本身開始的。 如果在此處找到,則根本不會查詢原型鏈。

現在,關於另一個為什么您的console.log()語句會打印其內容的問題,請注意,第一次調用是.toString()方法放在Plant原型上之前發生的。 完成此操作后,在console.log()調用中的+表達式中發生的從對象到字符串的轉換將隱式調用該函數以將原型對象轉換為字符串。

暫無
暫無

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

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