简体   繁体   English

如何在JavaScript中从一个对象文字调用函数到另一对象文字?

[英]How to call function from one object literal to other object literal in javascript?

I want to call function from one object literal to other object literal 我想从一个对象文字调用函数到另一个对象文字

// File name: file1.js
var common = {
    init: function() {
        this.function1();
    }
    function1: function() {
        // Here, I want to call function2 function from "other" object literal. 
        // How to do that?
    }
}
common.init();

// File name: file2.js
var other = {
    function2: function() {
    }
}

除了没有什么特别的事情:确保它们包含在要使用File1的HTML页面中,并且File2 File1 之前声明

Call common.init() after the other variable: other变量之后调用common.init()

var common = {
    init: function() {
        this.function1();
    },
    function1: function() {
        other.function2();
    }
};

var other = {
    function2: function() {
        alert('other.function2');
    }
};

common.init();

You would just function2 from the 'other' object from inside function1: 您只需从function1内部的“ other”对象中获取function2即可:

var common = {
    init: function() {
        this.function1();
    }
    function1: function() {
        other.function2();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM