Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - window as prototype makes setTimeout behave oddly

This question is related to my previous question (using window as a prototype returns seemingly wrong values in javascript) which was answered by @Stubb0rn, but I faced another problem:

function W(){
    var w=this;
    Object.defineProperty(this,'window',{configurable:true,enumerable:true,writable:false,value:w});
}
W.prototype=window;
window.setTimeout(function(){console.log("123")});     // works ok
(new W()).setTimeout(function(){console.log("123")});  // throws Uncaught TypeError: Illegal invocation(…)

please note I am using chrome to test

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Resolved it, it turns native functions needs to be called from within window context so I ended binding the functions in window and doing double prototyping like what follows:

function define(w){ // for testing I use requirejs define instead
    window.Test123=w;
}
(function(){
    function WBase(){
        for(var i in window){
            if(typeof window[i]=='function'){
                this[i]=window[i].bind(window);
            }
        }
    }
    WBase.prototype=window;
    function W(){
        var w=this;
        Object.defineProperty(this,'window',{configurable:true,enumerable:true,writable:false,value:w});
    }
    W.prototype=new WBase();
    define(function(){
        var windowAlias=new W();
        return (function(window){
            var ret={}; // returns only the variables added to the alias window object
            with(window){

                // CODE FROM MODULE HERE WILL HAVE an alias to "window" wich means if it adds variables to window (global scope) it will be prevented and instead added to the alias window

                for(var i in window){
                    if(window.hasOwnProperty(i)&&i!='window')
                        ret[i]=window[i];
                }
            }
            return ret;
        }).call(windowAlias,windowAlias)
    });
})();

Test123();  // for testing

try pasting jquery in place of comment (// CODE FROM MODULE HERE...), you'll get an object with properties jQuery and $ and they will not be added to the global scope. and I ended up creating a page that appends these lines dynamically for javascript files requested through querystring


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...