[英]In javascript, how do I call a class method from another method in the same class?
I have this: 我有这个:
var Test = new function() {
this.init = new function() {
alert("hello");
}
this.run = new function() {
// call init here
}
}
I want to call init
within run. 我想在运行中调用
init
。 How do I do this? 我该怎么做呢?
Use this.init()
, but that is not the only problem. 使用
this.init()
,但这不是唯一的问题。 Don't call new on your internal functions. 不要在内部函数上调用new。
var Test = new function() {
this.init = function() {
alert("hello");
};
this.run = function() {
// call init here
this.init();
};
}
Test.init();
Test.run();
// etc etc
Instead, try writing it this way: 相反,尝试这样写:
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()
Try this, 试试这个,
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
Thanks. 谢谢。
var Test = function() {
this.init = function() {
alert("hello");
}
this.run = function() {
this.init();
}
}
Unless I'm missing something here, you can drop the "new" from your code. 除非我在这里遗漏了什么,否则你可以从你的代码中删除“新”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.