calling eval() in particular context

前端 未结 14 1129
说谎
说谎 2020-11-27 17:05

I have following javaScript \"class\":

A = (function() {
   a = function() { eval(...) };
   A.prototype.b = function(arg1, arg2) { /* do something... */};
}         


        
14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 18:09

    definitely not the right answer, and please do not use with statement, unless you know what you're doing, but for the curious, you can do this

    Example

        var a = {b: "foo"};
        with(a) {
            // prints "foo"
            console.log(eval("b"));  
            
            // however, "this.b" prints undefined
            console.log(eval("this.b"));
        
            // because "this" is still the window for eval
            // console.log(eval("this")); // prints window
    
    // if you want to fix, you need to wrap with a function, as the main answer pointed out
            (function(){
    	         console.log(eval("this.b")); // prints foo
            }).call(a);     
        }
        
        // so if you want to support both    
        with (a) {
        	(function (){
            console.log("--fix--");
          	console.log(eval("b")); // foo
            console.log(eval("this.b")); // foo
          }).call(a);
        }

    with is the failed attempt to create block scopes within functions, kind of what the ES6's let is designed to do. (but not exactly, open and read the resource links)

提交回复
热议问题