function.js /* call和apply位于Function.prototype上,使用场景: 1、调用函数 2、将类数组对象转化成数组对象 3、借用别人的方法 4、绑定this的指向 5、继承 6、实现ES6扩展运算符功能*/function
/*
call和apply位于Function.prototype上,使用场景:
1、调用函数
2、将类数组对象转化成数组对象
3、借用别人的方法
4、绑定this的指向
5、继承
6、实现ES6扩展运算符功能
*/
function foo() {
console.log(this === window);
}
foo(); // true
foo.call(); // true
foo.apply(); // true
/*非严格模式下*/
foo.call(null); // true
foo.call(undefined); // true
// 2、将类数组对象转化成数组对象
function person(name, age, high) {
console.log(arguments);
var arr = [].slice.apply(arguments);
console.log(arr);
}
person('xiaoming', 12, '1.6m');
// 3、借用别人的方法
var arr = [1, 2, 3, 4, 5, 6];
Math.max.call(Math, arr); // 6
// 4、绑定this的指向
var foo = {
name: 'foo',
showName: function () {
console.log(this.name);
}
}
var bar = {
name: 'bar'
}
foo.showName.apply(bar); // 'bar'
// 5、继承
var Father = function (name, age, high) {
this.name = name;
this.age = age;
}
var Student = function (name, age, high) {
// 继承父类,调用父类构造函数
// 此处this指向Student对象实例
Father.call(this, name, age, high);
this.high = high;
}
Student.prototype.message = function () {
// 此处this指向Student对象实例
console.log("name: " + this.name + ",age: " + this.age + ",high: " + this.high);
}
new Student('xiaoming', 12, '1.6').message();
// 6、实现ES6扩展运算符功能
// console.log打印会拍平数组
(_console = console).log.apply(_console, [1, 2, 3]); // 1 2 3
// 只有Function才有prototype,包括new Object()也是根据传参调用具体的Function构造函数
