不使用此关键字的上下文中的javascript eval [英] javascript eval in context without using this keyword

查看:86
本文介绍了不使用此关键字的上下文中的javascript eval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在特定上下文中执行eval。我发现此处的答案很有用。但是,我在Chrome版本53.0.2785.143 m中收到以下行为。没试过其他浏览器。我使用的代码如下:

I am trying to execute eval within a particular context. I have found the answer here useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m. Not tried other browsers. The code I am using is the following:

function evalInContext(js, context) {
    return function() { return eval(js); }.call(context);
}


console.log(evalInContext('x==3', { x : 3})) // Throws
console.log(evalInContext('this.x==3', { x : 3})) // OK

但是我预计第一次调用 evalInContext 不要抛出。任何想法为什么会发生这种情况?

However I expected the first call to evalInContext not to throw. Any ideas why this might be happening?

推荐答案

范围和背景不一样



解析变量 x 的方式与上下文无关。它由范围规则解决:任何闭包是否定义了该变量?如果没有,请查看全局对象。在任何时候都不会通过查看上下文来解析变量。

Scope and Context are not the same

The way variable x is resolved has nothing to do with context. It is resolved by scope rules: does any of the closures define that variable? If not, look in the global object. At no point the variable is resolved by looking in the context.

你可以看看这篇文章

行为并非特定于 eval ,它与其他函数相同:

The behaviour is not particular to eval, it is the same with other functions:

"use strict";

var obj = { x : 3};
var y = 4;

function test() {
  console.log(this.x); // 3
  console.log(typeof x); // undefined
}

test.call(obj);

function test2() {
  console.log(this.y); // 4
  console.log(typeof y); // number
}

test2.call(window);

这篇关于不使用此关键字的上下文中的javascript eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆