[英]Setting an object's property value using object's method
Is There any way to set object property using object function? 有什么方法可以使用对象函数设置对象属性吗? Eg:
例如:
var Object={
init: function(){
this.newParam=alert("ok");// This should alert ok while called Object.newParam()
}
}
Thanks in advance. 提前致谢。
No it wouldn't get called as per your expectation. 不,不会像您期望的那样被调用。 It would get called during the time when the object is getting initialized.
在对象初始化期间将调用它。 And
obj.newParam
would have the returned value of alert("ok")
, ie] undefined
. 并且
obj.newParam
将具有alert("ok")
的返回值,即undefined
。
You have to rewrite your code like below to achieve what you want, 您必须像下面那样重写代码才能实现所需的功能,
var obj = {
init: function(){
this.newParam= function() {
alert("ok");// This should alert ok while called Object.newParam()
}
}
}
Also using name Object
for your variable is a riskier one when you are in the global context. 在全局环境中,将
Object
用作变量的名称也比较危险。
Try something like: 尝试类似:
var Object={
init: function(){
return {
newParam :function() {
alert("ok");// This should alert ok while called Object.newParam()
}
}
}
}
console.debug(Object.init().newParam());
Note that when init() is called it returns an object. 请注意,调用init()时,它将返回一个对象。 You can use that object and invoke newParam function from that -
Object.init().newParam()
您可以使用该对象并从该对象调用newParam函数
Object.init().newParam()
Fiddle at https://jsfiddle.net/krwxoumL/ 在https://jsfiddle.net/krwxoumL/中提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.