[英]javascript properties of methods
是否有可能在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.
函数基本上是对象,所以只要像得到它一样进行设置即可:
this.method = function() {
};
this.method.parameter = 'something_relevant';
另外,不要在表达式后消除分号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.