javascript关于call与apply方法详解

来源:互联网 发布:windows system 编辑:程序博客网 时间:2024/05/03 10:51

每一个函数都包含两个非继承而来的方法:call与apply。这两个方法的用途都是在特定的作用域中调用函数,也就是动态改变函数体内this对象。换句话说,可以将函数对象继承到当前上下文(this)中来使用。

官方示例1:

function Product(name, price) {  this.name = name;  this.price = price;}function Food(name, price) {  Product.call(this, name, price);  this.category = 'food';}function Toy(name, price) {  Product.call(this, name, price);  this.category = 'toy';}var cheese = new Food('feta', 5);var fun = new Toy('robot', 40);

官方示例2:

var person = {    firstName:"John",    lastName: "Doe",    fullName: function () {        return this.firstName + " " + this.lastName;    }}person.fullName();         // Will return "John Doe"var myObject = {    firstName:"Mary",    lastName: "Doe",}person.fullName.call(myObject);  // Will return "Mary Doe"

绑定一些函数用于传递参数

function sum(x , y){    return x+y;}function call1(num1 , num2){    return sum.call(this , num1 , num2);}function apply1(num1 , num2){    return sum.apply(this , [num1,num2]);}

扩充作用域

window.color = 'red';var obj = {color:'blue'};var obj2 = {color:'yellow'};function showColor(){    alert(this.color);}//showColor();  //red//showColor.call(window); //red//showColor.call(obj); //blue

可以做到方法与对象的解耦

call方法的简单模拟与实现

function test1(a , b){    return a+b;}// 自定义的对象(js中大写的函数名默认为自定义对象)function Obj(x, y){    this.x = x ;     this.y = y ;    return x*y;}var o = new Obj(10 , 20);o.method = test1 ;alert(o.method(o.x , o.y));delete o.method;test1.call(o,o.x ,o.y);   //200
阅读全文
0 0