access object property from object method in javascript
I have something like
var foo = function(arg){
var something = {
myPropVal: "the code",
myMethodProp: function(bla) {
// do stuff with mypropval here
alert(this) // => DOMWindow
}
}
}
开发者_StackOverflow社区
is this possible? can i access the contents of myPropVal from within myMethodProp given the
sure you can
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();
Yes, you can, below is an example.
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
In the context of an anonymous function used as property in an object, this
refers to the object and can be used to access other properties.
const robin = {
firstName: 'Robin',
lastName: 'Wieruch',
getFullName: function () {
return this.firstName + ' ' + this.lastName;
},
};
console.log(robin.getFullName());
// "Robin Wieruch"
You might have to reference it as something.myPropVal
.
精彩评论