Javascript:从函数对象内部调用对象函数

Javascript: Call object function from within a function object

本文关键字:对象 函数 调用 内部 Javascript      更新时间:2023-09-26

我的问题似乎是我的对象函数是不可见的,如果我从函数的对象内调用它。示例代码:

function foo()
{
   this.bar = function() 
              { 
                 alert("hit me!"); 
              }
   this.sna = { 
                 fu:   function () 
                       {
                          this.bar();
                       }
              };
}

this似乎指的是sna而不是foo。如何处理foo ?this.parent不工作

使用一个变量来引用this (Foo)。查看此- JavaScript | MDN

function Foo() {
    this.bar = function() {
        console.log("hit me!");
    };
    var that = this;
    this.sna = {
        fu: function() {
            that.bar();
        }
    };
}
var foo = new Foo();
foo.bar();
foo.sna.fu();

一个选项是添加对this的引用:

function foo() {
  var _t = this;
  this.bar = function() { };
  this.child = {
    this.foo = function() {
      _t.bar():
    };
  };
}