gpt4 book ai didi

Javascript 运行对象和所有这些方法

转载 作者:行者123 更新时间:2023-11-30 13:01:24 26 4
gpt4 key购买 nike

我创建了以下 jQuery OOP 代码

(function ($) {

example = {
method1 : function() {},
method2 : function() {}
};


})(jQuery);

我不想使用 init() 并在文档就绪时调用一些方法。有没有办法以文字表示法执行/运行对象?我使用了 var example = new Object(); 但我遇到了错误,我只需要与对象关联的所有方法就绪即可运行。

最佳答案

这样就可以了:)

(function ($) {

// define some methods
var example = {
method1: function() { console.log(1); },
method2: function() { console.log(2); }
};

// run all methods in example
for (var m in example) {
if (example.hasOwnProperty(m) && typeof example[m] === "function") {
example[m]();
}
}

// => 1
// => 2

})(jQuery);

如果你想使用新的比如

var example = new Example();
// => "A"
// => "B"

你可以这样做

(function($) {

var Example = function() {
this.initializeA();
this.initializeB();
};

Example.prototype.initializeA = function() {
console.log('A');
}

Example.prototype.initializeB = function() {
console.log('B');
};

// init
new Example();
// => "A"
// => "B"

})(jQuery);

关于Javascript 运行对象和所有这些方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17333639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com