簡體   English   中英

無法真正理解Javascript中的構造函數和原型關系

[英]Can't really understand constructor and prototype relationship in Javascript

我是Javascript的初學者,並且很難嘗試理解構造函數和原型屬性之間的關系。

我知道,原型對象有一個constructor指向構造函數屬性。 構造函數有一個prototype屬性,指向原型對象。

這是我想要了解的代碼(我的問題在代碼中被注釋):

function Car(){};
var myCar = new Car();
console.log(Object.getPrototypeOf(myCar)); //why this prints "Car" Object ? isn't it the constructor not the prototype object ? why the prototype object is not printed ?


var Vehicle = {
    getName : function(){
        return "hello";
    }
};
Car.prototype = Vehicle ; //I'm trying to change the prototype property in the constructor to "Vehicle" Object is that done right ?
console.log(Object.getPrototypeOf(myCar).getName()); //Why am i getting getName() function does not exist ?

為什么這會打印“汽車”對象? 不是構造函數不是原型對象嗎? 原型對象為什么不打印?

這就是Chrome(或您使用的瀏覽器)命名對象的方式。 如果仔細查看屬性,它實際上是Car.prototype

在此輸入圖像描述

我正在嘗試將構造函數中的prototype屬性更改為“Vehicle”對象是否做得對?

您無法更改現有對象的原型,只能擴展它。 設置Car.prototype = Vehicle; 只會更改Car 未來實例的原型,現有的實例仍會引用原始的原型對象,它沒有getName屬性:

// create a new instance after setting the new prototype
var myCar2 = new Car();
// yields false
console.log(Object.getPrototypeOf(myCar) === Object.getPrototypeOf(myCar2)); 

這實際上與原型無關,而是與JavaScript中的賦值和引用有關。 想象一下,我有以下對象:

var foo = {
    bar: {
        answer: 42
    }
};

並假設我將foo.bar分配給另一個對象的屬性:

var baz = {};
baz.xyz = foo.bar;

現在將foo.bar設置為其他值,如foo.bar = {} ,將不會更改baz.xyz的值,它仍將引用上一個對象。

擴展原始對象(擴展原型)或更改其屬性會產生影響,因為foo.barbaz.xyz指向同一個對象:

foo.bar.answer = 21;
console.log(baz.xyz.answer); // shows 21
// console.log(foo.bar === baz.xyz); // yields true

暫無
暫無

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

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