2016-12-10 40 views
1

我有這樣的代碼:Javascript繼承由兩個subclases

var first = function() { 
 
    this.loc = '1'; 
 
    this.test = function() { 
 
    console.log('first ' + this.loc); 
 
    } 
 
} 
 

 
var second = function() { 
 
    var me = this; 
 

 
    this.loc = '2'; 
 
    this.test = function() { 
 
    console.log('second ' + this.loc); 
 
    Object.getPrototypeOf(me).test.call(me); 
 
    } 
 
} 
 

 
second.prototype = new first(); 
 

 
var third = function() { 
 
    var me = this; 
 

 
    this.loc = '3'; 
 
    this.test = function() { 
 
    console.log('third ' + this.loc); 
 
    Object.getPrototypeOf(me).test.call(me); 
 
    } 
 
} 
 

 
third.prototype = new second(); 
 

 
var t = new third(); 
 
t.test();

它將輸出:

third 3 
second 3 
first 2 

我怎樣才能使它輸出:

third 3 
second 3 
first 3 

所以我想用最後一個繼承的類來覆蓋第一個類的loc值。

+0

這是有趣的是,使用ES6語義我們看到預期的行爲:https://repl.it/EmmE/2 –

回答

1

變化thisArg(簽名fun.call(thisArg[, arg1[, arg2[, ...]]]))從methis:我不知道它下面snipset會做你想要什麼,而不是

... 
var second = function() { 
    var me = this; 

    this.loc = '2'; 
    this.test = function() { 
     console.log('second ' + this.loc); 
     Object.getPrototypeOf(me).test.call(this); // <-- 
    } 
} 
... 

是怎麼回事:

第一次,test() func和灰是在third實例輸出"third 3"

然後,test函數是從second實例(該third原型)對在同一third例如通過Object.getPrototypeOf(me).test.call(me);

test功能正在執行this關鍵字應該指向被叫稱爲third實例,並傳遞給進一步test()呼叫

0

this指針second實際上是third.prototype。所以設置的secondthird.prototype)的loc財產

var first = function() { 
 
    this.loc = '1'; 
 
    this.test = function() { 
 
    console.log('first ' + this.loc); 
 
    } 
 
} 
 

 
var second = function() { 
 
    var me = this; 
 

 
    this.loc = '2'; 
 
    this.test = function() { 
 
    console.log('second ' + this.loc); 
 
    Object.getPrototypeOf(me).test.call(me); 
 
    } 
 
} 
 

 
second.prototype = new first(); 
 

 
var third = function() { 
 
    var me = this; 
 

 
    this.loc = '3'; 
 
    this.test = function() { 
 
    console.log('third ' + this.loc); 
 
    Object.getPrototypeOf(me).test.call(me); 
 
    } 
 
} 
 

 
third.prototype = new second(); 
 
third.prototype.loc = 3; 
 

 
var t = new third(); 
 
t.test();

0

您通過混合原型和this.x任務做與繼承一些有趣的事情。爲second對象函數調用

var first = function(num){ 
    this.num = num; 
} 

first.prototype.test = function(){ console.log("value " + this.num); } 

// test it 
var x = new first(10); 
x.test(); 

var second = function(){ 
    first.apply(this, arguments); 
} 
second.prototype = new first(); 
second.prototype.test2 = function(){ console.log("second " + this.num) }; 

// test it 
var y = new second(20); 
y.test() 

var third = function(){ 
    second.apply(this, arguments); 
} 
third.prototype = new second(); 
second.prototype.test3 = function(){ console.log("third " + this.num) }; 

// test it 
var z = new third(30); 
z.test() 
z.test2() 
z.test3()