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.method = function() {
this.parameter = 'abc'; // Set parameter on the object on which method() is called
this.method.parameter = 'xyz'; // Set parameter on the object representing the method itself
};
This shows the difference in accessing the property after the method is called
p.method();
console.log(p.parameter); // Display property of the object p, equals 'abc'
console.log(p.method.parameter); // Display property of the function object representing method(), equals 'xyz'
You should decide whether you need a property on the function object or on p
object. Note that the function object may be shared by a number of objects created by the Main()
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:
function Main() {
this.method = function() {
this.parameter = 'something_relevant'; // Set property on object on which method() is called.
};
}
var p = new Main();
p.method();
console.log(p.parameter); // Read property from object p.
If you intend to use a property defined on the function object representing method()
, your code should look similar to this:
function Main() {
this.method = function() {
this.method.parameter = 'something_relevant'; // Set property on function object representing method().
};
}
var p = new Main();
p.method();
console.log(p.method.parameter); // Read property from the function object.
Functions are objects basically, so just set it like you get it:
this.method = function() {
};
this.method.parameter = 'something_relevant';
Also, don't eliminate semicolons after expressions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.