您的位置:首页 > 移动开发

apply通过实例理解

2016-07-15 15:49 232 查看
测试->运行环境chrom console

>var aaa = {a:1,b:2,c:function(){console.log(this.a)}}

运行结果:undefined

>aaa.c();

运行结果:1

>var bbb = {a:10,b:20}

运行结果:undefined

>aaa.c.apply(bbb); //bbb对象执行aaa对象c()方法。c方法里面的this对象当然变成是bbb对象了。 通俗理解:bbb对象替换掉aaa对象,并执行方法。

运行结果:10

总结:

apply是function对象的一个方法。

apply作用:让参数对象执行其它对象方法的作用。

实例一
<script language="javascript">
function Person(name){

this.name=name;
this.sayname=function (){
alert(this.name);
}
}
function Student(name){
Person.apply(this,arguments);
}

var xiaoming=new Student("小明");
xiaoming.sayname();
</script>

实例二
<script language="javascript">
/**定义一个animal类*/
function Animal(){
this.name = "Animal";
this.showName = function(){
alert(this.name);
}
}
/**定义一个Cat类*/
function Cat(){
this.name = "Cat";
}

/**创建两个类对象*/
var animal = new Animal();
var cat = new Cat();

//通过call或apply方法,将原本属于Animal对象的showName()方法交给当前对象cat来使用了。
//输入结果为"Cat"
animal.showName.call(cat,",");
//animal.showName.apply(cat,[]);
</script>
  


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: