我有一个使用函数和密钥的javascript代码,我可以使用" this"对象,但我添加了一个部分jsonp来使用Web服务,我无法访问"这个"对象,强制更改所有代码以从窗口放置整个路径。这是我原来的代码:
(function () {
"use strict";
console.log("Hello World!");
window.programOne = window.programOne || {};
programOne = {
varS: {
var1: "One",
var2: null,
var3: "Two"
},
demo: function(data){
console.log( JSON.stringify(data) );
},
execute: function(values){
// Works correctly when calling from programOne.execute({ "item": "Lorem"});
//this.demo(values);
//> { "item": "Lorem"}
//this.varS.var2 = values;
//console.log(this.varS.var1);
console.log(this);
//It is necessary to use it with the callback. The "this" is undefined object.
//Does not work here inside "this" object?
// this.demo(values);
window.programOne.demo(values);
},
start: function(){
window.executeMyCB = programOne.execute;
var script = document.createElement('script');
script.src = "http://whatever.com/the/script.js&callback=executeMyCB";
document.getElementsByTagName('head')[0].appendChild(script);
}
};
// Demo
programOne.execute({ "item": "Lorem"});
programOne.start();
}());
可以访问对象的函数和变量,而无需使用" window"?从自己的脚本获取访问权限,但由于运行jsonp的函数(window.executeMyCB)不会让我使用"这个"。我认为,作为javascript的新手,我不太了解并调整此代码解决了我的错误,并理解我的问题/此对象的操作。
感谢
答案 0 :(得分:1)
使用Function.prototype.bind
将对象绑定到您创建的全局函数:
window.executeMyCB = programOne.execute.bind(programOne);
或尝试更改调用以通过对象访问方法。不确定这是否适用于您的服务:
"http://whatever.com/the/script.js&callback=programOne.execute"
由于您有jQuery标记,如果您支持旧版浏览器,也可以使用$.proxy
代替.bind()
。
window.executeMyCB = $.proxy(programOne, "execute");