javascript - 为什么 a.y 在这里未定义?

标签 javascript inheritance prototype

function A() {}
A.prototype.x = 10;

var a = new A();
alert(a.x); // 10

A.prototype = {
  x: 20,
  y: 30
};

alert(a.y) // undefined
  1. 为什么它委托(delegate)给 a.x 的旧原型(prototype) 而不是新的 一个?
  2. 为什么 a.y 抛出 undefined 是在 prototype 中设置的?

最佳答案

发生这种情况是因为您设置了A.prototype = obj

您没有向 a 继承的 Object 添加属性,而是创建了一个全新的对象作为 A.prototype而这个不是由 a

继承的

考虑一下,

function A() {}
A.prototype.x = 10;

var p1 = A.prototype; // keep reference to this

var a = new A();

A.prototype = {x: 20, y: 30};

Object.getPrototypeOf(a) === A.prototype; // false, not the new prototype
Object.getPrototypeOf(a) === p1; // true, the old prototype

// however
var b = new A();
Object.getPrototypeOf(b) === A.prototype; // true, this is the new prototype

如果您对旧原型(prototype)(我称之为 p1)的属性进行了更改,这些将被 a

继承

关于javascript - 为什么 a.y 在这里未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428271/

相关文章:

javascript 如何找到包含文本的 DOM 节点?

javascript - 将值从 HTML 页面传递到批处理文件

具有接口(interface)和默认实现的 C++ 继承

java - Java 类中的最终可选成员变量

javascript - 覆盖继承的原型(prototype)方法并在新方法中调用原始方法

javascript - 使用 Jquery 和 ajax 更新 HTML 表

php - 通过 Ajax 发送到 PHP 的 Fabric.js canvas.toDataURL()

java - 一个方法中的多个泛型

c++ - 虚拟公共(public)模式下从模板类继承的类的原型(prototype)

javascript - javascript中函数与函数的关系