gpt4 book ai didi

Javascript : can we reuse inner function to acces both global and local

转载 作者:行者123 更新时间:2023-11-30 15:56:43 25 4
gpt4 key购买 nike

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

有什么办法可以得到studio吗?通过使用相同的 getTeamName 函数。(即我知道,删除 this 将获取工作室。)而不删除这个?

最佳答案

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

  1. 使用调用:otherTeamName.getTeamName.call(window)
  2. 复制引用:

    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 : can we reuse inner function to acces both global and local,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38412729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com