我有这个:
var Test = new function() {
this.init = new function() {
alert("hello");
}
this.run = new function() {
// call init here
}
}
我想在运行中调用init
。我该怎么做?
答案 0 :(得分:7)
使用this.init()
,但这不是唯一的问题。不要在内部函数上调用new。
var Test = new function() {
this.init = function() {
alert("hello");
};
this.run = function() {
// call init here
this.init();
};
}
Test.init();
Test.run();
// etc etc
答案 1 :(得分:3)
相反,尝试这样写:
function test() {
var self = this;
this.run = function() {
console.log(self.message);
console.log("Don't worry about init()... just do stuff");
};
// Initialize the object here
(function(){
self.message = "Yay, initialized!"
}());
}
var t = new test();
// Already initialized object, ready for your use.
t.run()
答案 2 :(得分:2)
试试这个,
var Test = function() {
this.init = function() {
alert("hello");
}
this.run = function() {
// call init here
this.init();
}
}
//creating a new instance of Test
var jj= new Test();
jj.run(); //will give an alert in your screen
感谢。
答案 3 :(得分:1)
var Test = function() {
this.init = function() {
alert("hello");
}
this.run = function() {
this.init();
}
}
除非我在这里遗漏了什么,否则你可以从代码中删除“新”。