您的位置:首页 > 其它

4种函数调用方式

2016-12-08 15:33 169 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<script>
//1.函数执行模式
function add(a,b){
console.log(this);
return a+b;
}
add(1,2);//this等于window

//2.对象方法的调用模式
function Cat(){
this.show = function(){
console.log(this);
}
}
var c = new Cat();
c.show();//对象调用自己的方法
//this指向c对象
//所有的事件响应方法都是对象方法调用模式

//3.构造器调用模式
function Cat(){
this.show = function(){
console.log(this);
}
}
var c = new Cat();
//构造器调用模式:this指向构造出来的对象

//4.call和apply调用模式
function add(a,b){
this.result = a+b;
}
var p = {};//定义一个空对象
add.call(p,3,4);//在这个方法调用的时候,this指向p
console.log(p.result);
//apply 和 call 是一样的用法,只不过apply第二个参数用数组进行传递
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: