__proto__和Javascript中的继承

时间:2010-08-13 09:47:19

标签: javascript inheritance prototype

我一直在研究javascript继承几天,虽然我已经取得了很多进展,但还有一些我还不太了解的事情。

例如,我觉得这种行为很混乱:

var Employee = function Employee() { this.company = 'xyz'; };
var Manager = function Manager() { this.wage = 'high'; };

var m = new Manager();

m; // { "wage": "high", __proto__ : Manager } -- no problems so far.

Manager.prototype = new Employee();

var n = new Manager;

m.company; // undefined
n.company; // "xyz"

m的{​​{1}}属性指向的对象不是__proto__当前原型。 这有点违反直觉,因为:

  

即使在创建对象后将对象添加到其原型中,对象也会继承属性。

     

取自JavaScript: The Definitive Guide, 5th Edition, By David Flanagan

这种行为也不能适用于上述案例吗?

任何人都可以澄清吗?

1 个答案:

答案 0 :(得分:4)

这有点令人困惑,因为函数本身就是对象:

function Employee() {this.company = 'xyz';}
function Manager() {}

var m = new Manager();
Manager.prototype = new Employee();

/* You set the prototype on the Manager function (object), 
   your m instance and Manager function are separate objects.
   At this point the prototype of m is still undefined */

m = new Manager();
m.company; // 'xyz'

/* Creating a new Manager copies the new prototype */
相关问题