JavaScript重写constructor属性的问题

console.log("-----------------------使用原型实现继承---------------------------");
function Person() {

}
Person.prototype.dance = function () {};

function NinjaTestInherit() {}
//通过将NinjaTest的原型赋值给Person实例,实现NinjaTestInherit继承Person.
NinjaTestInherit.prototype = new Person();

const ninjaTestInherit = new NinjaTestInherit();
if (ninjaTestInherit instanceof NinjaTestInherit) {
  console.log("ninjaTestInherit receives functionally from the NinjaTestInherit proptype");
}
if (ninjaTestInherit instanceof Person) {
  console.log("... and the Person proptype");
}
if (ninjaTestInherit instanceof Object) {
  console.log("... and the Object proptype");
}
if (typeof ninjaTestInherit.dance === "function") {
  console.log("... and can dance!");
}

Person.prototype.sing = function () {}
if (typeof ninjaTestInherit.sing !== "function") {
  console.log("ninjaTestInherit can not sing!");
} else {
  console.log("ninjaTestInherit can sing!-->" + ninjaTestInherit.sing);
}

Person.prototype.dance = null;
if (ninjaTestInherit.dance != null) {
  console.log("ninjaTestInherit is not null-->!" + ninjaTestInherit.dance);
} else {
  console.log("ninjaTestInherit is null!-->" + ninjaTestInherit.dance);
}

if (ninjaTestInherit.constructor === NinjaTestInherit) {
  console.log("The ninjaTestInherit object was created by the NinjaTestInherit constructor");
} else {
  console.log("The ninjaTestInherit object was not created by the NinjaTestInherit constructor");
}

if (ninjaTestInherit.constructor === Person) {
  console.log("The ninjaTestInherit object was created by the Person constructor");
} else {
  console.log("The ninjaTestInherit object was not created by the Person constructor");
}

 

从上图发现,通过设置Person实例对象作为NinjaTestInherit构造器的原型时,我们丢失了NinjaTestInherit与NinjaTestInherit初始原型之间的关联。这是一个问题,因为constructor属性可用于检测一个对象是否由某一个函数创建的。

if (ninjaTestInherit.constructor === NinjaTestInherit) {

console.log("The ninjaTestInherit object was created by the NinjaTestInherit constructor");

} else {

console.log("The ninjaTestInherit object was not created by the NinjaTestInherit constructor");

}

通过上述方式测试:发现无法查找到NinjaTestInherit 对象的constructor属性。回到原型上,原型上也没有constructor属性,继续在原型链上追溯,在Person对象的原型上具有指向Person本身的constructor属性。事实上我们查找ninjaTestInherit 对象的构造函数,我们得到的答案是Person。

但实际上这个答案是错误的,这可能是某些严重缺陷的来源。

参考《JavaScript忍者秘籍》

猜你喜欢

转载自blog.csdn.net/zhangying1994/article/details/84892127