Javascript原型模式-反馈

Javascript Prototype Pattern - Feedback

本文关键字:反馈 模式 原型 Javascript      更新时间:2023-09-26

我正在从使用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();
};

你完全重写了原型。你不能用这种方式处理继承。

由于{}是一个对象,因此您隐式地继承了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 () {};