是否可以在 JavaScript 中设置方法内的属性?
例如
function Main() {
this.method = function() {
this.parameter = 'something_relevant'
}
}
var p = new Main()
p.method()
console.log(p.method.parameter)
我尝试了这个,它记录了“未定义”。与范围有关吗?
最佳答案
在 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
};
这显示了调用方法后访问属性的差异
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'
您应该决定是否需要函数对象或 p
对象上的属性。请注意,该函数对象可以由 Main()
构造函数创建的多个对象共享。因此,它的行为方式有点类似于 C++ 或 Java 等语言中的静态成员。
如果您打算使用对象上定义的属性,您的代码应类似于以下内容:
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.
如果您打算使用在表示 method()
的函数对象上定义的属性,您的代码应类似于以下内容:
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.
关于方法的 JavaScript 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8625202/