Javascript类的问题

时间:2013-10-08 11:09:42

标签: javascript

我正在玩javascript,所以这可能听起来像一个微不足道的问题。在这样的代码中:

function timeFunction(fn, nameOfFn){
var start = Date.now();
fn();
var end = Date.now();
var time = end - start;
console.log(nameOfFn + ' took ' + time + 'ms');
}

function Person(name){
this.name = name;
this.sayName = function(){
    console.log(this.name);
}
}

var bob = new Person('bob');
timeFunction(bob.sayName,'sayName');

输出是:

result
sayName took 7ms 

(每次运行代码的时间都会有所不同)

不确定'结果'来自何处以及为什么'Bob'未显示。

2 个答案:

答案 0 :(得分:4)

sayName()函数中this并不是您所期望的。它实际上是window,因此您正在记录window.name属性(在您的情况下恰好是“结果” - 我猜你会在jsfiddle中测试你的代码吗?)。

这是因为JavaScript中的this是根据函数的调用方式设置的,它不会自动成为函数“所属”的任何对象。 (事实上​​,函数根本不属于“对象” - 您的bob对象不“拥有”.sayName(),它只是对它有一个引用。)

MDN解释this in detail

让代码按照您期望的方式运行的一种方法是使用.bind() method

timeFunction(bob.sayName.bind(bob),'sayName');

答案 1 :(得分:2)

由于Bob方法this范围不同,因此未显示

sayName:尝试

function Person(name){
   var _this = this;

   this.name = name; 
   this.sayName = function(){
      console.log(_this.name);
   }
}

或者更好的是,使用bind()也是@nnnnnn在之前的回答中建议的。

(当我执行你的代码时,我看不到“结果”字符串,也许它来自另一段代码)