在JavaScript中,在函数内声明变量,为什么函数获得更高的优先级?

时间:2017-02-24 06:59:47

标签: javascript

    function bar() {
        return foo;
        foo = 10;
        function foo() {}
        var foo = 11;
    }
    console.log(typeof bar());

typeof bar返回功能?! 为什么不数?

3 个答案:

答案 0 :(得分:3)

Function只是引用了function bar() { return foo; // function foo() {} foo = 10; function foo() {} var foo = 11; } alert(typeof bar()); // function 所以它正在返回function bar() { return foo; // returns foo undefined as no value is assigned foo = 10; var foo = function () {} // referenced to variable var foo = 11; } alert(typeof bar()) // undefined

function bar() {
    foo = 10; 
    return foo; // 10
    function foo() {}
    var foo = 11;
}
alert(typeof bar()); // number 10

另一种情况

function bar() {
    foo = 10;
    return function () {
      return foo 
    }
    var foo = 11;
}
alert(typeof bar()()); // number 10

这里将返回数字

loss, critic_params = net.train(x1, x2, y)

这也将返回一个返回数字

的闭包函数
self.online_trainable_weights = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="c_hot")
# Note: the self.loss here is just a common squared error.
self.weights_grads = tf.gradients(self.loss, self.online_trainable_weights)
self.weights_grad_clipped, _ = tf.clip_by_global_norm(self.weights_grads, 5.0)
self.optimizer = tf.train.AdamOptimizer(self.lr_start)
grads_and_vars = zip(self.weights_grad_clipped, self.online_trainable_weights)
self.optimize_op = self.optimizer.apply_gradients(grads_and_vars)

def train(self, x1, x2, y):
    loss, params, _ = self.sess.run([self.loss, self.check_params, self.optimize_op], feed_dict={
    self.hot_in_s: x1,
    self.hot_in_a: x2,
    self.y: y
    })
    return loss, params

答案 1 :(得分:2)

你搞砸了回复:)。

这不是优先事项。它是关于你最后从函数返回的东西。改变他们,看看。你得到号码。

export default (a, b) => {
  return a + b;
};

This gives you number.

答案 2 :(得分:1)

此行为的原因是由于javascript中的提升。

当解释javascript时,首先处理任何变量定义,因此在函数范围内,调用的实际顺序是类似

function bar {
    var foo = 11;
    function foo() {}
    return foo;
}

提升首先定位var foo = 11声明,然后由{foo命名函数覆盖foo。因此return foo返回函数本身,而不是数值。

This is a good starting point to understand hoisting