2010-08-13 89 views
6

我一直在研究JavaScript繼承了幾天,儘管我已經取得了很多進展,但還是有一些我不太瞭解的東西。__proto__和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__proto__屬性指向的對象是不是Manager當前原型。 這是有點不現實的,因爲:

對象繼承屬性,即使它們在創建對象後添加到其原型。

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

兩者無法這一行爲被應用到上述情況,也?

任何人都可以澄清?

回答

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 */