[英]access object property from object method in javascript
我有类似的东西
var foo = function(arg){
var something = {
myPropVal: "the code",
myMethodProp: function(bla) {
// do stuff with mypropval here
alert(this) // => DOMWindow
}
}
}
这可能吗? 我可以从 myMethodProp 中访问 myPropVal 的内容吗?
你当然可以
var foo = function(arg){
var something = {
myPropVal: "the code",
myMethodProp: function(bla) {
// do stuff with mypropval here
alert(this) // => DOMWindow
alert(this.myPropVal);
}
}
alert(something.myMethodProp());
}
foo();
您可能必须将其引用为something.myPropVal
。
在用作对象中的属性的匿名函数的上下文中, this
指的是该对象并可用于访问其他属性。
const robin = {
firstName: 'Robin',
lastName: 'Wieruch',
getFullName: function () {
return this.firstName + ' ' + this.lastName;
},
};
console.log(robin.getFullName());
// "Robin Wieruch"
是的,你可以,下面是一个例子。
obj = { offset: 0, IncreaseOffset: function (num) { this.offset += num }, /* Do not use the arrow function. Not working! IncreaseOffset2: (num) => { this.offset += num } */ } obj.IncreaseOffset(3) console.log(obj.offset) // 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.