call() 方法是javaScript中每个函数原型链上的方法,
1、概述
call()
方法调用一个函数, 其具有一个指定的this
值和分别地提供的参数( 参数的列表
)。
call()
方法作用和apply()
作用类似,唯一区别,call()
接受若干参数,apply()
接收一个包含若干参数的数组
1.1、语法
fun.call(thisArg, arg1, arg2, ...)
1.1.1、 thisArg
在fun函数运行时指定的this值。需要注意的是,指定的this值并不一定是该函数执行时真正的this值,如果这个函数处于非严格模式下,则指定为null和undefined的this值会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象。
1.1.2、arg1, arg2, …
指定的参数列表。
1.1.3、 返回值
返回值是调用方法的返回值,若改方法没有返回值,则返回undefined
1.1.4、描述
可以通过call()
来实现继承,写一个方法然后让另一个对象继承它,而不是在新对象中重新写一下这个方法
call()
方法存在于在Function.prototype
上Function.prototype.call()
,因此每个 函数
都可以通过原型链继承下来。
2、作用
2.1、继承函数的属性和方法
// 1. 使用 call 继承方法和属性
function Person() {
this.name = 'person';
this.age = 24;
this.print = function(){
console.log('hello call!');
}
}
function Son(){
// 使 son 继承 Person 的方法和属性
Person.call(this);
this.study = 'study';
this.play = function(){
console.log('son play!');
}
}
var son = new Son();
console.log(son);
son.print() //hello call!
son.age// 24
通过控制台打印发现,此时 son
已经具有 Person
的方法和属性
2.2、使用call() 方法调用匿名函数
// 2. 使用call() 方法调用匿名函数
function Person() {
this.name = 'person';
this.age = 24;
this.print = function(){
console.log('hello call!');
}
}
(function(){
this.print();
}).call(new Person());
控制台打印
2.3、使用call() 方法调用函数并且指定上下文的this
function print() {
var message = [this.person, 'is an awesome', this.role].join(' ');
console.log(message);
}
var desc = {
person:'Douglas Crockford',
role:'Javascript Developer'
}
print.call(desc);