1

好的,这是我想要做的基础知识:

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又是我的修改覆盖了原始对象。

我怎样才能让它按我的预期工作?注意,jQuery/jQuery UI 解决方案很好,但我想要一个香草和一个 jQuery 版本来了解发生了什么!

我的代码的jsFiddle:http: //jsfiddle.net/YGa7p/

4

2 回答 2

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 类函数的文章。

于 2012-11-04T14:47:15.230 回答
1

为原型实例化新对象。这解决了这个问题。像 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();​
于 2012-11-04T15:21:34.427 回答