【问题标题】:Javascript inheritance: subtype prototype cannot visit super type's property/function [duplicate]Javascript继承:子类型原型无法访问超类型的属性/功能[重复]
【发布时间】:2016-08-10 00:46:30
【问题描述】:

我在下面有这段代码:

function me(){
    this.age=30,
    this.say=function(){return 'hello me'}
}
function child(){
    this.hobby='sports'
}
child.prototype=new me();
var son=new child();
son.prototype=new me();
console.log(son.age);//30
console.log(son.__proto__.age);//30
console.log(son.constructor.prototype.age);//undefined
console.log(son.constructor.prototype.say())//exception

打印结果是,只有前2条日志打印出“30”,其他都打印出“undefined”,最后一行甚至在运行时抛出异常。

(1) 我期待他们都应该给我输出。为什么第三行打印“未定义”?

(2) 我希望 "proto" 和 "constructor.prototype" 具有相同的效果,但实际上并非如此。

【问题讨论】:

  • 您没有创建新的son。我建议和你的妻子谈谈。
  • 我刚刚修好了,见上面更新了,还是有问题。

标签: javascript constructor prototype instance proto


【解决方案1】:

son.constructor === meme.prototype 没有属性 agesay。注意son.__proto__.hasOwnProperty("constructor") === false

您将对象分配给本身没有构造函数属性的原型,这在访问 son.constructor 时会产生一些不直观的结果。是son.__proto__.__proto__.constructor,这可能不是您想要的。

显示此行为的示例:

function A() {}
function B() {}
console.log("Automatically added: " + A.prototype.constructor.toString());
A.prototype = new B();
let a = new A();
console.log("a constructor: " + a.constructor.toString());
if (a.constructor
    && !a.hasOwnProperty("constructor")
    && !a.__proto__.hasOwnProperty("constructor"))
  console.log("constructor property of a is further up the prototype chain!");

另请注意,您将new me() 作为原型分配给两个不同的对象,这是不必要的,也可能不是您想要的。

最后是一个工作示例:

function me(){
    this.age=30,
    this.say=function(){return 'hello me'}
}
function child(){
    this.hobby='sports'
}
child.prototype=new me();
child.prototype.constructor = child;
var son=new child();

console.log(son.age);
console.log(son.__proto__.age);
console.log(son.constructor.prototype.age);
console.log(son.constructor.prototype.say())

【讨论】:

  • 谢谢,只有一个问题,为什么我们需要'child.prototype.constructor = child'。我想在创建对象时,会自动为其分配一个构造函数属性,对吧?
  • 在声明函数时,会自动添加prototype.constructor,见spec。覆盖 prototype 时,这是 afaik 不会自动读取的。
  • 在函数上使用new时,位于prototype的对象将被添加到返回对象的内部[[Prototype]]属性中,该属性通过__proto__暴露,但是应该使用小心mozilla doc
猜你喜欢
  • 2023-03-16
  • 2020-11-16
  • 2018-07-12
  • 1970-01-01
  • 2019-03-08
  • 2019-11-18
  • 2019-01-24
  • 2016-07-04
  • 1970-01-01
相关资源
最近更新 更多