如何创建一个非常基本的'插件'

How to create a very basic 'plugin'?

本文关键字:插件 一个 何创建 创建 非常      更新时间:2023-09-26

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);

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

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/

您缺少一个用于设置所传递值的构造函数。以下是如何做到这一点:

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();
}

试试这个小提琴

您正在混合使用不同的方法在javascript中创建对象。你想要的可能就是林赫德利的答案。这是另一种方式(或者更确切地说是其他方式中的一种),它也会起作用,但不必要地复杂,并且只允许您拥有一个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);