如何调用在对象范围内声明的javascript函数?

时间:2016-01-03 11:42:38

标签: javascript function scope

var john = {

    peter: {},

    one: function() { alert('one'); },

    two: function() {
        peter.handler = function() {
            one(); // JS cannot find one(). one() undefined.

            Console.log(this); // object peter
        }

        Console.log(this); // object john
    }
}

如何在one()内使用peter.handler

5 个答案:

答案 0 :(得分:1)

您可以使用HERE.method_name()来访问函数调用的上下文,该函数调用(通常)是指定函数的对象,但在代码中的某个位置显式指定(HERE通常情况下)。

没有办法(没有循环遍历所有变量和测试)以了解其他对象具有john作为其中一个属性的值。

识别one(获取two的先决条件)的唯一方法是在handlerjohn函数中明确引用它。

答案 1 :(得分:0)

尝试使用对象 john.one(); 本身调用javascript函数。

例如: -

<强> <div class="chat-message error">Message example here</div> <div class="chat-message error">Message example here</div> <div class="chat-message error">Latest message</div>

答案 2 :(得分:0)

您可以随时执行此类操作并使用john.one()

进行调用
{{1}}

答案 3 :(得分:0)

要访问父对象,您应该使用关键字

请参阅以下更新代码:

var john = {

    peter: {},

    one: function() { alert('one'); },

    two: function() {
        this.peter.handler = function() {
            one(); // JS cannot find one(). one() undefined.

            console.log(this); // parent object: peter
        };

        console.log(this); // object john
      this.one();
    }
};

john.two();

答案 4 :(得分:0)

您可以使用如下

var john = {

    peter: {},

    one: function() { alert('one'); },

    two: function() {
        this.peter.handler = function() {
            john.one(); // JS cannot find one(). one() undefined.

            console.log(this); // object peter
        }

        console.log(this.peter.handler()); // call peter handler
    }
}