Javascript jQuery 创建对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6279036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery create object
提问by Tom Gullen
This is a simple question I know, I've looked on google but can't find much help. I'm trying to create an object, with my own custom parameters, and then call one of them in an alert.
这是我知道的一个简单问题,我在谷歌上看过,但找不到太多帮助。我正在尝试使用我自己的自定义参数创建一个对象,然后在警报中调用其中一个。
Whatever I try, doesn't seem to work, I know this is pretty simple stuff and I appologise! All my other JS in my time have been pretty simple and all inline because of that, I'm moving on to more OOP JS now.
无论我尝试什么,似乎都不起作用,我知道这是非常简单的事情,我道歉!我当时所有的其他 JS 都非常简单并且都是内联的,因此我现在正在转向更多的 OOP JS。
$.fn.DataBar = function() {
$.DataBar.defaultOptions = {
class: 'DataBar',
text: 'Enter Text Here'
}
this.greet = function() {
alert(this.text);
};
}
var q = new $.DataBar();
q.greet();
回答by David Tang
You don't need the
fnpart, simply use:$.DataBar = function () { ... };$.fnis simply a reference to jQuery's internal prototype. So$.fn.DataBaris intended to be used as$(selector).DataBar(), not$.DataBar().Your default options aren't being applied to the newly created object. Optionally, you can also define the
greetfunction onDataBar's prototype:$.DataBar = function () { $.extend(this, $.DataBar.defaultOptions); }; $.DataBar.prototype.greet = function () { alert(this.text); }; $.DataBar.defaultOptions = { class: 'DataBar', text: 'Enter Text Here' };
您不需要该
fn部分,只需使用:$.DataBar = function () { ... };$.fn只是对 jQuery 内部原型的引用。So$.fn.DataBar旨在用作$(selector).DataBar(),而不是$.DataBar()。您的默认选项不会应用于新创建的对象。或者,您还可以在的原型
greet上定义函数DataBar:$.DataBar = function () { $.extend(this, $.DataBar.defaultOptions); }; $.DataBar.prototype.greet = function () { alert(this.text); }; $.DataBar.defaultOptions = { class: 'DataBar', text: 'Enter Text Here' };
回答by DanielB
There are 43 problems in your code
您的代码中有43 个问题
a missing;after the default options (not causing the error)- add the default options to the instance with
this.defaultOptions - call
alert(this.defaultOptions.text) - instantiate with
$.fn.DataBar()as you added your class to$.fn
;默认选项后缺少一个(不会导致错误)- 将默认选项添加到实例中
this.defaultOptions - 称呼
alert(this.defaultOptions.text) $.fn.DataBar()当您将类添加到时实例化$.fn
Here your code working:
这里你的代码工作:
$.fn.DataBar = function() {
this.defaultOptions = {
class: 'DataBar',
text: 'Enter Text Here'
};
this.greet = function() {
alert(this.defaultOptions.text);
};
};
var q = new $.fn.DataBar();
q.greet();

