1. 程式人生 > >javaScript 函式的方法call() 使用詳解

javaScript 函式的方法call() 使用詳解

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.prototypeFunction.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);

在這裡插入圖片描述