var teamName ="studio";
var otherTeamName ={
    teamName :'factory',
    getTeamName : function(){
        alert(this.teamName);
    }
};
window.otherTeamName.getTeamName();// alerts factory


有什么方法可以获取studio吗?通过使用相同的getTeamName函数。

最佳答案

对的,这是可能的。有两种方法:


使用callotherTeamName.getTeamName.call(window)
复制参考:

var getTeamName = otherTeamName.getTeamName;
getTeamName(); // alerts studio



较旧的浏览器不支持call(),第二种解决方案适用于任何地方。



var teamName = "studio";

var otherTeamName = {
    teamName: 'factory',
    getTeamName: function() {
        alert(this.teamName);
    }
};
otherTeamName.getTeamName(); // alerts factory

var getTeamName = otherTeamName.getTeamName;
getTeamName(); // alerts studio

关于javascript - Javascript:我们可以重用内部函数来访问全局和本地,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38412729/

10-11 12:26