在javascript中,如何从同一类中的另一个方法调用类方法?
我有这个:在javascript中,如何从同一类中的另一个方法调用类方法?,javascript,class,methods,Javascript,Class,Methods,我有这个: var Test = new function() { this.init = new function() { alert("hello"); } this.run = new function() { // call init here } } 我想在run中调用init。我如何做到这一点?使用this.init(),但这不是唯一的问题。不要在你的内部功能上调用新的 var Test = n
var Test = new function() {
this.init = new function() {
alert("hello");
}
this.run = new function() {
// call init here
}
}
我想在run中调用init
。我如何做到这一点?使用this.init()
,但这不是唯一的问题。不要在你的内部功能上调用新的
var Test = new function() {
this.init = function() {
alert("hello");
};
this.run = function() {
// call init here
this.init();
};
}
Test.init();
Test.run();
// etc etc
除非我在这里遗漏了什么,否则您可以从代码中删除“new”。试试这个
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
谢谢。相反,试着这样写:
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()
中没有类或类方法JavaScript@ChrisBallance这不是显式正确的..但是有了它,我不能从另一个类调用
Test.init()
。如何使Test
成为一个单例,但仍然能够以这种方式调用init()
?对我来说很好,firebug不会抱怨。您是否从测试内部的函数声明中删除了“new”?您忘了从顶部函数中删除新函数。。。构造函数是否可以使用class
更新ES6的此答案?我想知道。谢谢这很好。。。不
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()