我目前正在学习JS对象并尝试对属性执行基本减法,然后通过方法输出。但是,即使typeof
告诉我currentAge
和currentYear
是数字,对象方法也会返回NaN的值。我做错了什么?我怎样才能得到以下方法来输出正确的数字?
var today = new Date();
var year = today.getFullYear();
var Sam = {
age: 27, //Number
birthMonth: "March", //March
currentYear: year, //number
birthYear: this.currentYear - this.age,
// Method to say birth year
sayBirthYear: function(){
console.log("I was born in the year " + this.birthYear );
//return NANS
}
}
Sam.sayBirthYear(); // Outputs Birth year

答案 0 :(得分:0)
上下文game === 3
不是引用当前对象switch
,而是引用封闭上下文,在本例中是this
上下文。
另一种方法是使用函数,并从中创建对象。这样,封闭的上下文就是函数:
Sam
答案 1 :(得分:0)
this.currentYear - this.age
执行时this
不是Sam
引用的对象。实际上,该对象尚未创建,currentYear
和age
在此时不能作为任何对象的属性。您可以通过几种方法来实现所需的行为。
您可以在创建对象后添加birthYear属性,如下所示:
var today = new Date();
var year = today.getFullYear();
var Sam = {
age: 27,
birthMonth: "March",
currentYear: year,
// Method to say birth year
sayBirthYear: function(){
console.log("I was born in the year " + this.birthYear );
}
}
Sam.birthYear = Sam.currentYear - Sam.age;
Sam.sayBirthYear(); // Outputs Birth year

或者您可以在对象创建期间执行此操作:
var today = new Date( );
var year = today.getFullYear( );
var Sam = new function ( ) {
this.age = 27;
this.birthMonth = "March";
this.currentYear = year;
this.birthYear = this.currentYear - this.age;
// Method to say birth year
this.sayBirthYear = function ( ) {
console.log( "I was born in the year " + this.birthYear );
};
};
Sam.sayBirthYear( ); // Outputs Birth year

或者你可以生下这样的吸气剂:
var today = new Date();
var year = today.getFullYear();
var Sam = {
age: 27,
birthMonth: "March",
currentYear: year,
get birthYear() { return this.currentYear - this.age; },
// Method to say birth year
sayBirthYear: function(){
console.log("I was born in the year " + this.birthYear );
}
}
Sam.sayBirthYear(); // Outputs Birth year

答案 2 :(得分:0)
在JavaScript中,this
默认为window
:
john = { whoami: this }
john.whoami // window
您必须将其放入一个能够更改其值的函数中:
function whoami () { return this; }
john = { whoami: whoami }
jack = { whoami: whoami }
whoami() // window
john.whoami() // john
jack.whoami() // jack
whoami.call(john) // john
whoami.call(jack) // jack