javascript在对象中获取值

Not*_*123 2 javascript

我得到了一个关于函数编写的测验:

/* ====== can not modify this line below till next dividing line ========= */
function foo() {
    var obj = {
        x : 1,
        y : 2,
        bar : bar()
    }

    function bar() {
/* ====== can not modify this line above ================================= */

        /* so how can I get obj.x and obj.y here and returns their sum ..? */

/* ====== can not modify this line below till next dividing line ========= */
    }
    return obj;
}

console.log( foo().bar ); // expected 3 
/* ====== can not modify this line above ================================= */
Run Code Online (Sandbox Code Playgroud)

我自己找到了两种方法,一种是获取foo.toString()并做一些REGEX魔术.

另一个是注册一个全局变量,比如只window.run控制foo()一次运行.

但是我想知道有没有其他方法可以解决这个问题?

谢谢你的回复〜

Ber*_*rgi 5

你不能.bar在构造对象之前调用,obj将是undefined以前属性(12)的已评估值仅在内存中不可访问.另请参见对象文字声明中的自引用.

鉴于你在一个具有相当任意限制的测验中发现了这个问题,他们似乎期待一个特技答案.有几种方法:

  • 访问源代码并自己评估对象文字
  • 简单地返回一个常量,给定obj.x并且obj.y在给定代码中也是常量
  • console.log例如,覆盖以进行出价

    function bar() {
        var log = console.log.bind(console);
        console.log = function(p) {
            log(p.valueOf());
        };
        return {
            valueOf: function() {
                return obj.x + obj.y;
            }
        };
    }
    
    Run Code Online (Sandbox Code Playgroud)

    不幸的是,由于console.log之前被解除引用而无法工作foo().
    类似的方法适用于可以自定义console.log行为而无需覆盖任何内容的环境:

    function bar() {
        return {
            inspect: function() {
                return String(obj.x + obj.y);
            }
        };
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 只是打电话给foo()自己获取值,但不要无限地递归bar:

    function bar() {
        if (foo.stop) return null;
        foo.stop = true;
        var res = foo().x + foo().y;
        foo.stop = false;
        return res;
    }
    
    Run Code Online (Sandbox Code Playgroud)