I have something like
var foo = function(arg){
var something = {
myPropVal: "the code",
myMethodProp: function(bla) {
// do stuff with mypropval here
alert(this) // => DOMWindow
}
}
}
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();
您可能必须将其引用为something.myPropVal
。
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"
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.