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

call和apply的使用

时间:2015-11-07 00:50:32      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:

call和apply的用途

1、传递参数

 

call和apply的第一个参数都是待绑定的对象,第二个参数有差别

//call使用的参数是可变参数
//apply使用的参数是数组
function sum() {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}

function Obj(x, y) {
this.x = x;
this.y = y;
}

var obj = new Obj(10, 20); //这种方式就是把函数指向交给了obj

var result = sum.call(obj, obj.x, obj.y);

var result2 = sun.apply(obj, [obj.x, obj.y]);
console.log(result);

console.log(result2);

2、扩展作用域--由绑定对象的作用域范围决定

var student = {name: ‘zjy‘};

var teacher = {name: ‘mr.zhao‘};

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

showName.call(student);
showName.call(teacher);

3、使用call,apply实现继承

 

function Animal() {
this.hoal = function() {
console.log("aaa");
}
}

function Cat() {
Animal.call(this);
}

var cat = new Cat();
cat.hoal();

function Tiger() {
Cat.apply(this);
}

var tiger = new Tiger();
tiger.hoal();

4、简单模拟一下call实现

 

function sum() {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}

function Obj(x, y) {
this.x = x;
this.y = y;
}
//简单的call的模拟
sum.mycall = function(obj) {
if (arguments.length == 0) {
console.log("必须传入一个绑定对象");
} else {
return this(arguments[1], arguments[2]);
}
}
console.log(sum.mycall(obj, obj.x, obj.y));

对于call和apply能够实现代码的解耦,便于程序的拓展。

 

call和apply的使用

标签:

原文地址:http://www.cnblogs.com/zhaojunyang/p/4943986.html

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