JavaScript命名空间+ Setter

时间:2014-06-03 12:05:49

标签: javascript

好吧,我在JavaScript中使用面向对象,但是我只是从命名空间中调用方法,而不是使用new。目前,我有以下代码:

var Component = {
    Button: function(_text, use_image) {
        button = $.createElement('button')
        if (use_image != false)
        {
            button.innerHTML = _text;
        }
        else
        {
            button.innerHTML = _text
        }
        var text = _text
        return button
    }
}

当我想要返回一个按钮时,我会这样做:

x = Component.Button("Click me")

之后我可以使用x。但是,如果我想更改x的文本,我必须使用x.textContent。我想实例化这个并使用setter来应用它的文本,这样:

x = new Component.Button("Click me")
x.text = "Don't click me"
document.getElementsByTagName("body")[0].appendChild(x)

如果我尝试应用setter text,它会变成全局的,我希望每个按钮都有一个唯一的。使用get / set混合命名空间。

提前谢谢

2 个答案:

答案 0 :(得分:0)

一种方式可能是,我不确定这是否是最好的方法。寻找更多答案

var Component = {
    Button: function(_text, use_image) {
        var button = {
            node : document.createElement('button'),
            setText : function(txt){this.node.innerHTML = txt;}
        };        
        if(_text){button.setText(_text);}
        return button;
    }
};

x = Component.Button("Click me");
x.setText("Don't click me");
document.getElementsByTagName("body")[0].appendChild(x.node);

y = Component.Button("Click me2");
y.setText("Don't click me2");
document.getElementsByTagName("body")[0].appendChild(y.node);

http://jsfiddle.net/2LCyn/

答案 1 :(得分:0)

这样的事情怎么样:

var Component = (function($){

    var buttonCount = 0;

    function Button(text, use_image){
        this.id = ++buttonCount;
        this.text = text;
        this.use_image = use_image;
        this.$element = $('<button/>').text(text);
        this.bindEvents();
    }

    Button.prototype.bindEvents = function(){
        var that = this;
        this.$element.on('click', function(){
            console.log('hello, I\'m button ' + that.id);
        });
    };

    Button.prototype.setText = function(text){
        this.text = text;
        this.$element.text(text);
    };

    return {
        Button: Button
    }

})(jQuery);

var button1 = new Component.Button('hello', false);
button1.setText('helloooo');
$('body').append(button1.$element);

var button2 = new Component.Button('world', true);
$('body').append(button2.$element);

http://jsfiddle.net/ATmAx/1/