var teamName ="studio";
var otherTeamName ={
teamName :'factory',
getTeamName : function(){
alert(this.teamName);
}
};
window.otherTeamName.getTeamName();// alerts factory
有什么方法可以获取
studio
吗?通过使用相同的getTeamName
函数。 最佳答案
对的,这是可能的。有两种方法:
使用call
:otherTeamName.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/