动态生成的方法

dynamically generated methods

本文关键字:方法 动态      更新时间:2023-09-26

在Pro javascript Technique book

中找到这个例子
function User( name, age ) {
    var year = (new Date()).getFullYear()-age;
    this.getYearBorn = function(){
        return year;
    };
}
var user = new User( "Bob", 44 );
alert(user.getYearBorn());  //system date is 2010 ,alerts 1967

我将系统日期更改为2012

alert(user.getYearBorn()); //alerts 1968.
根据上面的逻辑,我写了下面的代码
function Test(bornTime){
    var ageInMillis = new Date().getTime()-bornTime.getTime();
    this.age = function(){
        console.log("age:"+ageInMillis);
    }
}
var t = new Test(new Date());
t.age(); //output is zero
setTimeout(t.age,1000) // it prints 0

不应该第二次调用t.t age打印1000,我做错了什么吗?

不重新计算ageInMillis;当你调用new时,它将输出它是什么。

为了得到你期望的行为,你需要这个:

function Test(bornTime) {
    this.age = function() {
        var ageInMillis = new Date().getTime() - bornTime.getTime();
        console.log("age:" + ageInMillis);
    }
}

当您执行var t=new Test(new Date());并设置为0时计算ageInMillis。之后的任何调用都会返回0

你应该像下面这样修改你的函数,

function Test(bornTime) {
  var ageInMillis; //=new Date().getTime()-bornTime.getTime();
  this.age = function() {
      ageInMillis = new Date().getTime() - bornTime.getTime();
      console.log("age:" + ageInMillis);
  }
}
var t = new Test(new Date());
t.age(); //output is zero
setTimeout(t.age, 1000); // it prints 0
这里的

jsFiddle

创建对象时正在设置变量。它在所有时间内都是相同的值。如果你想改变它,你应该把它变成一个函数。你的代码实际上是工作的,只是你得到了当前时间,并从中减去了当前时间。更改传入的日期

var ageInMillis=function() {
    Date().getTime()-bornTime.getTime()
};

好吧,让我们看看你在做什么。

var t=new Test(new Date());

好的,现在你正在创建一个新的对象,bornTime是。

var ageInMillis=new Date().getTime()-bornTime.getTime();

bornTime是现在,你从现在减去它。任何数减去相同的数都是零,所以…我想你的问题现在很明显了

您正在传递一个新的Date()给Test(),它被设置为当前时间。然后从当前时间Date().getTime()-bornTime.getTime()中减去它,因为经过的时间少于一毫秒,差值为0毫秒。

当您在一秒钟后第二次调用它时,变量没有改变。您需要在"动态方法"(它实际上在JavaScript中称为匿名函数)中重做减法