使用'这个'对象构造函数

时间:2016-11-09 20:13:43

标签: javascript scope this

我对调用'这个'时得到的结果感到有点困惑。对象构造函数内部的变量。

function Slider(tag){
    this.tag = document.querySelector(tag),
    this.start = function(){
        return this.interval;
    },
    this.interval = setInterval(function(){
        console.log(this.tag); //undefined
        console.log(this); //window object
    }, 2000)
}
var route ={
    init:function(){        
        mySlide = new Slider('slider');
        mySlide.start();
    }
}
document.addEventListener('DOMContentLoaded', route.init);

我记录了标记console.log(this.tag),但它返回undefined,并且在this内记录console.log(this)变量时,它引用了窗口对象。

Here is a Demo

问题:为什么没有console.log(this.tag)返回所选元素?

2 个答案:

答案 0 :(得分:1)

setInterval中匿名函数的范围是Window。 如果你想让它成为Slider实例,你应该先bind它。

function Slider(tag){
this.tag = document.querySelector(tag),
this.start = function(){
    return this.interval;
},
this.interval = setInterval(function(){
    console.log(this.tag); //undefined
    console.log(this); //window object
}.bind(this), 2000)
}

答案 1 :(得分:1)

这是因为当您将回调函数传递给def generate_random_hyperparams(lr_min, lr_max, kp_min, kp_max): '''generate random learning rate and keep probability''' # random search through log space for learning rate random_learng_rate = 10**np.random.uniform(lr_min, lr_max) random_keep_prob = np.random.uniform(kp_min, kp_max) return random_learning_rate, random_keep_prob 时,它会在全局范围内调用。这就是为什么run_modeldef run_model(random_learning_rate,random_keep_prob): # Note that the arguments is named differently from the placeholders in the graph graph = tf.Graph() with graph.as_default(): # graph here... learning_rate = tf.placeholder(tf.float32, name='learning_rate') keep_prob = tf.placeholder(tf.float32, name='keep_prob') # other operation ... with tf.Session(graph=graph) as session: tf.initialize_all_variables().run() # session here... feed_train = {data: batch_data, #placeholder variable names as dict key, python value variables as dict value learning_rate: random_learning_rate, keep_prob : random_keep_prob } # evaluate performance with random_learning_rate and random_keep_prob performance = session.run([...], feed_dict = feed_train) return performance

您可以使用Function.bind()performance_records = {} for i in range(10): # random search hyper-parameter space 10 times random_learning_rate, random_keep_prob = generate_random_hyperparams(-5, -1, 0.2, 0.8) performance = run_model(random_learning_rate, random_keep_prob) performance_records[(random_learning_rate, random_keep_prob)] = performance 对象设置函数的上下文,并使其按您的意愿运行。

setInterval

另外,我只想指出this什么都不做。当你拨打window时,就是你的间隔时间。您的this只返回intervalID(仅用于this.interval = setInterval(function(){ console.log(this.tag); }.bind(this), 2000); )。实际上,因为你甚至没有使用mySlide.start();的返回值,所以调用它是没用的。

更新:另一种解决方案是在构造函数中使用new Slider('slider'),然后在mySlide.start();内使用clearInterval()

mySlide.start();

更新:如果您使用的是支持"arrow functions"的浏览器,则可以执行以下操作:

var self = this;