无法真正理解Javascript中的构造函数和原型关系

Raf*_*del 3 javascript constructor prototype

我是Javascript的初学者,并且很难尝试理解构造函数和原型属性之间的关系.

我知道Prototype对象有一个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 ?
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 6

为什么这会打印"汽车"对象?不是构造函数不是原型对象吗?原型对象为什么不打印?

这就是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)); 
Run Code Online (Sandbox Code Playgroud)

这实际上与原型无关,而是与JavaScript中的赋值和引用有关.想象一下,我有以下对象:

var foo = {
    bar: {
        answer: 42
    }
};
Run Code Online (Sandbox Code Playgroud)

并假设我分配foo.bar给另一个对象的属性:

var baz = {};
baz.xyz = foo.bar;
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)