码迷,mamicode.com
首页 > 移动开发 > 详细

js中的call()方法与apply()方法

时间:2017-04-22 00:08:50      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:window   其他   参数   style   指定   无法   .sh   没有   erro   

    摘自:http://blog.csdn.net/chelen_jak/article/details/21021101

在web前端开发过程中,我们经常需要改变this指向,通常我们想到的就是用call方法

一、call方法的定义

关于call的定义都很拗口。在我的理解,a.call(b,arg1,arg2..)就是a对象的方法应用到b对象上。例如如下例子:

function add(a,b)
{
alert(a+b);
}
function reduce(a,b)
{
alert(a-b);
}
add.call(reduce,1,3) //将add方法运用到reduce,结果为4

二、call可以改变this指向

如下例:

function b()
{
alert(this)
}
b(); //window
b.call(); //window
b.call(“a”,2,3); //a

再看一个复杂的例子:

function Animal()
{
this.name=”animal”;
this.showName=function()
{
alert(this.name)
}
}
function Cat()
{
this.name=”cat”;
}
var animal = new Animal();
var cat = new Cat();
animal.showName(); //结果为animal
animal.showName.call(cat); //原本cat没有showName方法,但是通过call方法将animal的showName方法应用到cat上,因此结果为cat

三、实现继承

如下例子:

function Animal(name)
{
this.name=name;
this.showName=function()
{
alert(this.name)
}
}
function Cat(name)
{
Animal.call(this,name); //将Animal应用到Cat上,因此Cat拥有了Animal的所有属性和方法
}
var cat = new Cat(“Black Cat”);
cat.showName(); //浏览器弹出Black Cat

四、apply用法

apply和call的用法只有一个地方不一样,除此之外,其他地方基本一模一样

a.call(b,arg1,arg2…)

apply(b,[arg1,arg2]) //apply只有2个参数,它将call的参数(arg1,arg2…)放在一个数组中作为apply的第二参数

 

其他总结:

call方法: 
语法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]]) 
定义:调用一个对象的一个方法,以另一个对象替换当前对象。 
说明: 
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。 

apply方法: 
语法:apply([thisObj[,argArray]]) 
定义:应用某一对象的一个方法,用另一个对象替换当前对象。 
说明: 
如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 
如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

 

代码示例:

function Animal(name) {
    this.name = name;
    this.showName = function() {
        console.log(this.name);
    };
}

function Cat(name) {
    Animal.call(this, name);
}
Cat.prototype = new Animal(); //prototype 属性使您有能力向对象添加属性和方法。

function Dog(name) {
    Animal.apply(this, name);
}
Dog.prototype = new Animal();

var cat = new Cat("Black Cat"); //call必须是object

var dog = new Dog(["Black Dog"]); //apply必须是array

cat.showName();
dog.showName();

console.log(cat instanceof Animal);
console.log(dog instanceof Animal);

 

js中的call()方法与apply()方法

标签:window   其他   参数   style   指定   无法   .sh   没有   erro   

原文地址:http://www.cnblogs.com/LChenglong/p/6746443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!