JavaScript——方法

1、定义方法

方法就是把函数放在对象的里面,对象只有两个东西 : 属性和方法

var jjh = {
    name: '姜嘉航',
    bitrh: 1996,
    // 方法
    age: function () {
        // 今年 - 出生的年
        var now = new Date().getFullYear();
        return now-this.bitrh;
    }
}
//属性
jjh.name  //姜嘉航
//方法,一定要带  ()
jjh.age() //24

this.代表什么? 拆开上面的代码看看~

function getAge() {
    // 今年 - 出生的年
    var now = new Date().getFullYear();
    return now-this.bitrh;
}

var jjh = {
    name: '姜嘉航',
    bitrh: 1996,
    age: getAge
}

jjh.age()   //24
getAge()  NaN   window

注意:this是无法指向的,是默认指向调用它的那个对象;

2、apply

在javascript中可以控制 this 指向!

function getAge() {
    // 今年 - 出生的年
    var now = new Date().getFullYear();
    return now-this.bitrh;
}

var jjh= {
    name: '姜嘉航',
    bitrh: 1996,
    age: getAge
};

var xiaoming = {
    name: '小明',
    bitrh: 2000,
    age: getAge
};

jjh.age() //24

getAge.apply(xiaoming,[]);// this,指向了 xiaoming,参数为空
posted @ 2020-01-15 14:15  Godlesss  阅读(124)  评论(0编辑  收藏  举报