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作用:让参数对象执行其它对象方法的作用。
>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>
相关文章推荐
- Android工具类之App相关辅助类
- 学习Android的点点滴滴--button click事件处理
- Android Material Design(一)史上最全的材料设计控件大全
- Android Material Design(一)史上最全的材料设计控件大全
- 详解android:scaleType属性
- Android 圆形头像的截取
- iOS:基于AVPlayer实现的视频播放器
- 文字跑马灯效果
- android studio 代码混淆如何忽略第三方jar包 The same input jar is specified twice
- 解读Unity中的CG编写Shader系列目录
- 解读Unity中的CG编写Shader系列三
- 解读Unity中的CG编写Shader系列二
- android ScrollView 滚动到顶部
- 解读Unity中的CG编写Shader系列一
- 2016最新FFmpeg-iOS静态库编译
- WebView
- Android实现对图片的缩放、剪切、旋转、存储
- Android 生成带图片的二维码
- Android自定义View之画笔与画布
- 从Immutable来谈谈对于线程安全的理解误区