为什么更改JavaScript原型对象会更改构造函数值?

时间:2015-01-18 04:30:14

标签: javascript prototype

所以我的问题实际上是在代码中。请参阅以下部分:



function Person(){};
function Ninja(){};

// Creating ninja object
var ninja = new Ninja();
console.log("ninja constructor with empty prototype object = " +
    ninja.constructor);

// Attaching new prototype to Ninja
Ninja.prototype = new Person();
console.log("ninja constructor with prototype(Person) = " +
    ninja.constructor);

// The previous console.log printed out the correct value. Now for the
// confusing part! For every other new Ninja object the constructor is no more
// Ninja
var ninja1 = new Ninja();
console.log("ninja1 constructor with prototype(Person)= " +
    ninja1.constructor);

var anotherNinja = new Ninja();
console.log("anotherNinja constructor with prototype(Person)= " +
    anotherNinja.constructor);

console.log("Again ninja constructor with prototype(Person)= " +
    ninja.constructor);




新对象的构造函数如何指向Person?它们最初是由忍者创造的。这发生在我改变Ninja的原型之后。

然而,我在更改原型之前创建的前一个Ninja对象仍然适用,即使原型已更改,其构造函数仍指向Ninja。

1 个答案:

答案 0 :(得分:0)

constructor属性返回对创建实例原型的对象的引用。它不是包含创建它的函数名称的字符串值。