javascript对象属性申请所有对象

时间:2013-12-05 06:47:41

标签: javascript

这是我的HTML

    <!-- language: lang-js -->
    window.onload = function(){
    var a = new color(document.getElementById('red'),{weight:'bold'});
    var b = new color(document.getElementById('green'));
    }

这是我的javascript

    <!-- language: lang-js -->
    (function (w) {
    function obj(element, source) {
        this.element = element;
        this.options = this.extend(this.defaults, source);
        this._init();
        console.log(this.defaults);
    }
    obj.prototype = {
        extend: function (destination, source) {
            for(var k in source) {
                if(source.hasOwnProperty(k)) {
                    destination[k] = source[k];
                }
            }
            return destination;
        },
        defaults: {
            color: 'red'
        },
        _init: function () {
            this.element.style.color = this.options.color;
            if(this.options.weight) {
                this.element.style.fontWeight = this.options.weight;
            }
            this._initEvent();
        },
        _initEvent: function () {
            var o = this;
            this.element.onmouseover = function () {
                o._mouseOver(this);
            }
            this.element.onmouseout = function () {
                o._mouseOut(this);
            }
        },
        _mouseOver: function (j) {
            j.style.border = "1px solid " + this.options.color;
        },
        _mouseOut: function (j) {
            j.style.border = "1px solid transparent";
        }
    }
    w.color = obj;
})(window)

这是我的结果

<p>Object { color="red", weight="bold"}</p>
<p>Object { color="red", weight="bold"}</p>

我的问题

我的问题在这里,我只为对象“a”提供了'weight:bold`属性。但它也应用了对象“b”。它应该只适用于“a”。请帮我解决这个问题

1 个答案:

答案 0 :(得分:0)

您正在改变原型上的共享对象,因此它会针对所有实例进行变异,以防止您执行以下操作:

function obj(element, source) {
    this.element = element;
    this.options = this.extend({color:"red"}, source);
    this._init();
    console.log(this.defaults);
}

还有另一种保留默认值的解决方案:

function obj(element, source) {
    this.element = element;
    this.options = this.extend({}, this.defaults);
    this.extend(this.options, source);//extend will mutate this.options
    this._init();
    console.log(this.defaults);
}

有关原型的更多信息,请参阅this answer