Section 2.7: Object and Methods

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值