JSONP 并反对这个

JSONP and object this

我有一个使用函数和键的 Javascript 代码,我可以将其与“this”对象一起使用,但我添加了一部分 JSONP 来使用 Web 服务,但我无法访问“this” " 对象,强制更改所有代码以放置来自 window 的整个路由。这是我的代码原件:

(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”指定?从自己的脚本中获取,但是由于函数(window.executeMyCB)运行 JSONP不会让我使用this。我认为作为 Javascript 的新手,我不是很了解并且修改此代码解决了我的错误,并理解了我的 question/operation 这个对象。

使用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");