Is it possible in javascript to set properties inside methods?
For example
function Main() {
this.method = function() {
this.parameter = 'something_relevant'
}
}
var p = new Main()
p.method()
console.log(p.method.parameter)
I tried this and it logs ‘undefined’. Is it about scope?
Inside
method()you’re setting a property of the object on which the method is called rather than on the function object representing the method.This shows the difference inside the method:
This shows the difference in accessing the property after the method is called
You should decide whether you need a property on the function object or on
pobject. Note that the function object may be shared by a number of objects created by theMain()constructor. Hence it will behave in a manner somewhat similar to a static member in languages like C++ or Java.If you intend to use property defined on the object, your code should look similar to this:
If you intend to use a property defined on the function object representing
method(), your code should look similar to this: