如何创建一个非常基本的“插件”?

时间:2013-07-11 23:29:27

标签: javascript

Fiddle!

我正在尝试创建一个非常基本的'插件',如果你甚至可以这样称呼它。我希望能够使用这一行var box = new colorBox(node, options);(在JS的末尾)来编辑div#thing1的样式。我认为我的问题是调用我设置的功能。我不想要调用colorBox.setSize()来产生初始效果,但我希望能够稍后调用它,如果我想在设置colorBox原型的对象之后。谢谢!

HTML:

<div id="thing1"></div>
<div id="thing2"></div>

JS:

var colorBox = {
    setSize: function(){
        node.style.width = options.width + 'px';
        node.style.height = options.height + 'px';
    },
    setColor: function(){
        node.style.backgroundColor = options.color;
    },
    setSize(),
    setColor()
}

var node = document.getElementById('thing1');
var options = {
    color: 'red',
    width: 200,
    height: 200
}

var box = new colorBox(node, options);

3 个答案:

答案 0 :(得分:3)

使用构造函数创建一个新对象:

var colorBox = function(node, options) {
    this.setSize = function(){
        node.style.width = options.width + 'px';
        node.style.height = options.height + 'px';
    };
    this.setColor = function(){
        node.style.backgroundColor = options.color;
    };
    this.setSize();
    this.setColor();
}

var node = document.getElementById('thing1');
var options = {
    color: 'red',
    width: 200,
    height: 200
}

var box = new colorBox(node, options);

小提琴:http://jsfiddle.net/e7gX8/1/

答案 1 :(得分:0)

您缺少一个构造函数来设置您传递的值。这是你如何做到这一点:

var colorBox = function(node, options) {
    this.setSize = function(){
        node.style.width = options.width + 'px';
        node.style.height = options.height + 'px';
    };

    this.setColor = function(){
        node.style.backgroundColor = options.color;
    };
    this.setSize();
    this.setColor();
}

Try in this fiddle

答案 2 :(得分:0)

您正在混合使用javascript制作对象的不同方法。你想要的可能是Lyn Headley的答案。这是另一种方式(或者更确切地说是其他方式之一),它也可以工作但是不必要地复杂化并且只允许你有一个colorBox(但是对于其他情况可能有用)。

var colorBox = {
    setSize: function(){
        this.node.style.width = this.options.width + 'px';
        this.node.style.height = this.options.height + 'px';
    },
    setColor: function(){
        this.node.style.backgroundColor = this.options.color;
    },
    initialize: function(node, options) {
        this.node = node;
        this.options = options;
        this.setSize();
        this.setColor();
    }
}

var node = document.getElementById('thing1');
var options = {
    color: 'red',
    width: 200,
    height: 200
}
colorBox.initialize(node, options);
相关问题