面向对象编程

1. This关键字

这三个方法都可以绑定this值

1. call()

  • this

    1
    2
    3
    4
    5
    6
    7
    8
    var obj = {};

    var f = function () {
    return this;
    };

    f() === window // true
    f.call(obj) === obj // true

    call方法的参数,应该是一个对象。
    如果参数为空、null和undefined,正常模式下默认传入全局对象(window),严格模式下为undefined。
    call方法可以改变this的指向,指定this指向对象obj。

    1
    2
    3
    4
    5
    var f = function () {
    return this;
    };

    f.call(5) //Number {[[PrimitiveValue]]: 5}

    若call方法的参数是一个原始值,那么这个原始值会转成对应的对象

  • arguments

    1
    2
    3
    4
    5
    6
    function add(a, b) {
    console.log(arguments[0]);
    console.log(arguments[1]);
    }

    add.call(this, 1, 2) // 1,2,第一个参数传给this,后面的都存入arguments对象

    arguments是伪数组

2. apply()

apply方法的第一个参数用法和call一样,不同的是第二个参数必须是一个数组

1
2
3
4
function f(x, y){
console.log(x + y);
}
f.apply(null, [1, 1]) // 2

所以利用这一点
(1)找出数组最大元素
JavaScript 不提供找出数组最大元素的函数。结合使用apply方法和Math.max方法,就可以返回数组的最大元素。

1
2
var a = [10, 2, 4, 15, 9];
Math.max.apply(null, a) // 15

(2)将数组的空元素变为undefined
通过apply方法,利用Array构造函数将数组的空元素变成undefined。

1
2
Array.apply(null, ['a', ,'b'])  
// [ 'a', undefined, 'b' ]

数组的forEach方法会跳过空元素,但是不会跳过undefined。

3. bind()

bind可以绑定this值

1
2
3
4
5
var d = new Date();
d.getTime() // 1481869925657

var print = d.getTime;
print() // Uncaught TypeError: this is not a Date object.

这样会报错,可以像下面这样,将getTime内部的this绑定为d对象

1
2
var print = d.getTime.bind(d);
print() // 1481869925657

下面这样也是,将inc方法内部的this绑定到counter

1
2
3
4
5
6
7
8
9
10
var counter = {
count: 0,
inc: function () {
this.count++;
}
};

var func = counter.inc.bind(counter);
func();
counter.count // 1

还可以绑定其他对象

1
2
3
4
5
6
7
8
9
10
11
12
13
var counter = {
count: 0,
inc: function () {
this.count++;
}
};

var obj = {
count: 100
};
var func = counter.inc.bind(obj);
func();
obj.count // 101

bind还可以绑定原函数的参数

1
2
3
4
5
6
7
8
9
10
11
var add = function (x, y) {
return x * this.m + y * this.n;
}

var obj = {
m: 2,
n: 2
};

var newAdd = add.bind(obj, 5); //5相当于绑定了add函数里的x
newAdd(5) // 20,这个5相当于add函数里y

若bind第一个对象为null,等于将this绑定到全局对象(window)
bind的注意事项:
(1)每一次返回一个新函数
bind方法每运行一次,就返回一个新函数,所以监听事件的时候,要谨慎使用。更多

2. 用函数模拟一个类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Animal(species) {
this.species = species; //自有属性
}

Animal.prototype = {
constructor: Animal,
walk : function () {}, //走路的代码
run: function () {}, //跑步的代码
eat: function () {}, //吃东西的代码
sleep: function () {} //睡觉的代码
};

let cat = new Animal('cat')

cat.specise === cat //true
//并且cat对象的__proto__指向Animal.prototype,有里面的动作属性

加new的三个作用

  • 帮你创建临时对象,用this就可以访问到,比如上面的this.species
  • 帮你绑定原型,使Animal里有个隐藏属性__proto__指向Animal.prototype
  • 帮你return临时对象Animal.prototype.constructor === Animal

未完待续…