[英]Call instance method by self.method in Javascript
在Javascript中有這樣的對象
SomeClass = {
methodOne: function(){
if ( SomeClass.methodTwo() ){
doSomething();
}
},
methodTwo: function(account){
doSomethingElse()
}
我想打電話給self.methodTwo()
代替SomeClass.methodTwo()
在methodOne
身上,就像這將是在Python。 我該怎么做?
請不要在JavaScript中使用“類”一詞,JS是一種基於原型的繼承語言,因此您應該這樣編寫:
var myPrototype = {
methodOne: function () {
console.log('Invoking method one');
if (this.methodTwo()) {
doSomething();
}
},
methodTwo: function (account) {
console.log('Inovking method two')
}
}
var instance = Object.create(myPrototype);
當然,您可以使用ES6“類”語法糖(並在ES5中將其轉換為瀏覽器),但是我真的不喜歡它(盡管使用了新關鍵字,但ES6中仍然沒有類)。
您可以通過this
方法訪問第二種方法:
var SomeClass = {
methodOne: function(){
if(this.methodTwo){
console.log('first');
}
},
methodTwo: function(){
console.log('second');
}
};
在這種情況下, this
指的是在其中聲明函數的對象。
像這樣?
SomeClass = function() {
this.methodOne = function (){
if ( this.methodTwo('') ){
doSomething();
}
}
this.methodTwo = function (account){
doSomethingElse()
}
}
var instance = new SomeClass();
alert(instance.methodOne());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.