从javascript中的对象方法访问对象属性

Nat*_*Nat 2 javascript

我有类似的东西

var foo = function(arg){
  var something = {
    myPropVal: "the code",
    myMethodProp: function(bla) {
      // do stuff with mypropval here
      alert(this) // => DOMWindow
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?我可以从 myMethodProp 中访问 myPropVal 的内容吗?

Car*_*ard 8

是的,可以,下面是一个例子。

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
Run Code Online (Sandbox Code Playgroud)

  • 这个答案值得一些爱。无论出于何种原因,箭头功能在这种情况下都不起作用 - 非常好!++1 (2认同)

i10*_*100 6

你当然可以

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();
Run Code Online (Sandbox Code Playgroud)

  • “this”是什么取决于调用函数的上下文。所以你可能会更安全地使用 `something`。 (2认同)