JS添加到函数而不是用原型替换

时间:2016-04-15 20:27:29

标签: javascript javascript-objects

base = {
    init : function() {
        console.log('initiate')
    }
}

function Plugin(){
    this.init = function() {
        console.log('init me');
    }
}

Plugin.prototype = base;

x = new Plugin();

x.init();

我希望它能同时控制日志,我希望能够在基本变量中设置一组默认函数,并在函数插件中添加它们。

https://jsfiddle.net/eqzwbdww/

2 个答案:

答案 0 :(得分:0)

不确定这是否是最佳解决方案,但解决了它:

base = {
    init : function() {
       console.log('initiate')
    }
}

function Plugin(){
    this.init = function() {
       Plugin.prototype.init.call(this);
       console.log('init me');
    }
}

Plugin.prototype = base;

x = new Plugin();

x.init();

答案 1 :(得分:0)

另一种解决方案,也不确定这是否是最好的解决方案。

base = {
    init : function() {

        document.write(' initiate ')
    }
}

function Plugin(){
    this.init = function() {
    	this.__proto__.init ();
        document.write(' init me ');
    }
}
Plugin.prototype = base;

x = new Plugin();

x.init();