2012-11-04 77 views
1

好了,這裏是我所想要做的基本知識:在jQuery中克隆和擴展對象?

var Hi = function(name){ 
    this.name = name; 
}; 

Hi.prototype = { 
    message: function(){ 
     $('body').append('Hi '+this.name); 
    } 
}; 

var hi = new Hi('There '); 

的正常工作,但現在我想複製它,所以我可以改變它說「再見」,

var Bye = Hi; 
Bye.prototype.message = function(){ 
    $('body').append('Bye '+this.name); 
}; 

var bye = new Bye('There'); 

所以後來得到的Hi There Bye There輸出我認爲這應該工作:

hi.message(); 
bye.message(); 

而是輸出Bye There Bye There又名我修改s覆蓋原始對象。

我該如何得到這個工作,因爲我期望?請注意,jQuery/jQuery UI解決方案沒問題,但我想要一個vanilla和一個jQuery版本來理解正在發生的事情!

的的jsfiddle我的代碼:http://jsfiddle.net/YGa7p/

回答

2

var Bye = Hi; 

不只是提供原始的功能,它不會複製。 通常你做

var Hi = function(name){ 
    this.name = name; 
}; 

Hi.prototype.message = function() { 
    $('body').append('Hi '+this.name); 
}; 

var Bye = function(name){ 
    Hi.call(this, name); // re-call base constructor 
}; 

Bye.prototype = new Hi(); // create base object 

// overwrite Hi's message 
Bye.prototype.message = function() { 
    $('body').append('Bye '+this.name); 
}; 

var hi = new Hi("there"); 
var bye = new Bye("there"); 

// See also instanceof: 

// hi instanceof Hi  // true 
// hi instanceof Object // true 

// bye instanceof Bye // true 
// bye instanceof Hi  // true 
// bye instanceof Object // true 

http://jsfiddle.net/YGa7p/1/

在javaScript中,很難做到OOP。爲了創建派生對象,使用'簡單'方法會遇到麻煩,至少在級別3 ... n繼承中。如果您對javaScript中的擴展繼承感興趣,請閱讀我的文章V javaScript class functions

1

Instantiage原型的新對象。解決了這個問題。像Bye.prototype = new Hi();

var Hi = function(name) { 
    this.name = name; 
}; 

Hi.prototype = { 
    message: function() { 
     $('body').append('Hi ' + this.name); 
    } 
}; 

var hi = new Hi('There '); 

var Bye = Hi; 
Bye.prototype=new Hi(); 
Bye.prototype.message = function() { 
    $('body').append('Bye ' + this.name); 
}; 

var bye = new Bye('There'); 

hi.message(); 
bye.message();​