Javascript原型模式 - 反馈

时间:2013-05-21 20:24:23

标签: javascript jquery design-patterns

我正在使用Javascript揭示模块模式切换,我下面的内容似乎有效。我想知道的是,如果我正在做的是正确的,它是否遵循最佳实践。例如,我保持'this'状态并在构造函数中调用init函数的方式是正确的吗?

var testApp = function(){
    //Kick it off
    this.init();
};

testApp.prototype = {
    getUsers: function(callback){
        //do stuff
    },
    buildUserTable: function(data){
        //do stuff
    },
    refreshTable: function(){
        //Example
        this.getUsers();
    },
    init: function(){
        //Preserve 'this'
        var instance = this;
        //Callback + init
        this.getUsers(function(data){
            instance.buildUserTable(data);
        }); 
        $('.formSection .content').hide();
        $('.formSection .content:first').slideDown('slow').addClass('selected');
    }
};

window.onload = function () {
    var form = new testApp();
};

1 个答案:

答案 0 :(得分:2)

你完全覆盖原型。你无法以这种方式处理继承。

由于{}是一个对象,因此您隐式继承自Object,但没有别的。

继承如下所示:

function A() {};
function B() {};
B.prototype = new A();
var b = new B();
console.log(b instanceof A); // "true"

B现在继承自AObject

如果你现在这样做:

B.prototype = {
    foo: function () {}
};

var b = new B();
console.log(b instanceof A); // "false"

您不再继承A;

如何向原型添加功能?使用这种表示法:

B.prototype.foo = function () {};
相关问题