JSONP 和反对这个

Posted

技术标签:

【中文标题】JSONP 和反对这个【英文标题】:JSONP and object this 【发布时间】:2015-04-08 16:42:24 【问题描述】:

我有一个使用函数和键的 javascript 代码,我可以将其与“this”对象一起使用,但是我添加了一部分 JSONP 来使用 Web 服务,并且我无法访问“this”对象,从而强制更改从窗口放置整个路线的所有代码。这是我的原始代码:

(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)不会让我使用this。我认为作为 Javascript 的新手,我不太了解,修改此代码解决了我的错误,并了解我对这个对象的问题/操作。

【问题讨论】:

【参考方案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");

【讨论】:

谢谢。它工作正常,我现在正在阅读 bind 以了解它为什么工作

以上是关于JSONP 和反对这个的主要内容,如果未能解决你的问题,请参考以下文章

jsonp

跨域的问题(jsonp和cors)

Jsonp的使用

同源策略:JSONP和CORS

如何使用PHP和jquery获取jsonp?

Json & Jsonp