Section 2.6 讲解了Object的创建,object的property属性。 这节我们讲 Object 和 Methods的关系。
Object不仅仅可以储存property,同样可以保存methods。而且,只有object可以引入方法。
Very basic method in object. only object has methods
var alan = {
firstName: 'Alan', //key:value
lastName: 'Ning',
birthYear: 1990,
family:['Faye', 'Aiden', 'Nison'],
job: 'Front-end Developer',
isMarried: true,
calculateAge:function(birthYear){
return 2018 - birthYear;
}
}
console.log(alan.calculateAge(1980)); //result 28
在我们使用object的方法的时候,我们可以用 alan.calculateAge(1980) 来调用,我们需要传入值给calculateAge。这里有人就会问,这个age在object中已经定义了,如何直接使用呢?这里就会先涉及到this的用法。
We have to pass the value into the function. but the 1990 is alreday defind. so how do we use it?
var alan = {
firstName: 'Alan', //key:value
lastName: 'Ning',
birthYear: 1990,
family:['Faye', 'Aiden', 'Nison'],
job: 'Front-end Developer',
isMarried: true,
calculateAge:function(){
return 2018 - this.birthYear;
}
}
console.log(alan.calculateAge());
alan.age = alan.calculateAge(); //insert a value age into object alan.
console.log(alan);
上面的步骤就是如何使用this。 this是指,当alan使用function calculateAge的时候,function内部的this就指向了alan。所以this.birthYear 就是指alan.birthYear. 但是同时有一个问题来了,我们使用 alan.age = alan.calculateAge(); 把age加入了alan中,有没有什么办法代替这一步呢?
所以就有了另一个this:
var alan = {
firstName: 'Alan', //key:value
lastName: 'Ning',
birthYear: 1990,
family:['Faye', 'Aiden', 'Nison'],
job: 'Front-end Developer',
isMarried: true,
calculateAge:function(){
this.age = 2018 - this.birthYear;
}
}
alan.calculateAge(); //without this call, the result do not include the value age.
console.log(alan)
this.age就指向了alan.age。 相当于上一步中的 alan.age
同时需要注意的是,如果直接 console.log(alan) 的话,function是没有运行的,所以结果中是没有age属性的。所以在这之前我们需要call这个function:alan.calculateAge();