Having such object in Javascript
SomeClass = {
methodOne: function(){
if ( SomeClass.methodTwo() ){
doSomething();
}
},
methodTwo: function(account){
doSomethingElse()
}
I want to call self.methodTwo()
instead of SomeClass.methodTwo()
in methodOne
body, like it would be in Python.
How can I accomplish this?
答案 0 :(得分:2)
Please don't use the word 'Class' in JavaScript, JS is a prototype based inheritance language, so you should write this this way:
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);
You could use ES6 'class' syntactic sugar (and transpile it in ES5 for browser), sure, but I don't really like it (there is still no class in ES6, despite the new keywords).
答案 1 :(得分:0)
You can access the second method via this
:
var SomeClass = {
methodOne: function(){
if(this.methodTwo){
console.log('first');
}
},
methodTwo: function(){
console.log('second');
}
};
In this case, this
refers to the object within which the function are declared.
答案 2 :(得分:0)
Like this?
SomeClass = function() {
this.methodOne = function (){
if ( this.methodTwo('') ){
doSomething();
}
}
this.methodTwo = function (account){
doSomethingElse()
}
}
var instance = new SomeClass();
alert(instance.methodOne());