为什么这里没有定义?

Sha*_*ane 10 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
Run Code Online (Sandbox Code Playgroud)
  1. 它为什么委托给old prototype of a.x新的而不是新的?
  2. 为什么要a.y投掷undefinedprototype

Pau*_* S. 11

这是因为发生的事情,当你设置A.prototype = obj

您创建了一个全新的对象,而不是向继承的对象添加属性,而这个对象不会被继承.aA.prototypea

考虑,

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

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