6

如果在文字对象中我尝试在嵌套属性/函数中使用“this”引用函数,则这不起作用。为什么?嵌套属性有自己的范围吗?

例如,我想从 d.f2 内部调用 f1:

var object = {    

  a: "Var a",
  b: "Var b",
  c: "Var c",

  f1: function() {
    alert("This is f1");
  },

  d: {
      f2: function() {
       this.f1();
    }
  },

  e: {
      f3: function() {
        alert("This is f3");
     }
  }
}

对象.f1(); // 工作
对象.d.f2(); // 不工作。对象.e.f3(); // 工作

谢谢,安德里亚。

4

2 回答 2

9

thisd里面f2而不是object。您可以存储对对象的引用,或object直接调用,或使用call/apply来调用函数并明确告诉它this该函数内部的含义:

object.d.f2.call(object); // now this refers to object inside f2
于 2010-04-18T10:28:48.647 回答
4

根据@slaver113 的想法,这是一种不改变thisinside上下文的替代方法:f2()

var object = (function() {
  var _this = {
    f1: function() {
      alert('This is f1');
    },
    d: {
      f2: function() {
        _this.f1();
      }
    }
  }

  return _this;
})();

object.d.f2(); // Alerts 'This is f1'
于 2013-09-18T05:33:06.810 回答