【javascript】 function.apply 菜鸟学习笔记
来源:互联网 发布:php7编译 nginx 编辑:程序博客网 时间:2024/06/04 23:33
今天无意看到 function有个apply的函数于是就去看看 发现很好玩 在这里分享下 先看看参数
apply方法能劫持另外一个对象的方法,继承另外一个对象的属性 Function.apply(obj,args)方法能接收两个参数 obj:这个对象将代替Function类里this对象 args:这个是数组,它将作为参数传给Function(args-->arguments)
--args的数组就会一个个的变成那个方法的参数好啦 现在来看看apply的用法
1)使用apply来简单实现js的继承 上代码
function Person(name){ this.name= name, this.eat= function(){ document.writeln(this.name); } } function child (name,age){ Person.apply(this,arguments), this.age=age } child.prototype.fly= function(where){ document.writeln(where) } ; var a = new child("pc",12); a.fly(" house") ; a.eat("sweet ")输出结果
house pc
class child是没有eat方法的使用apply就可以简单的实现继承
=====================分割线=============================
要注意的是Person如果使用prototype的方法不能被继承? 上代码吧
function Person(name){ this.name= name } Person.prototype.eat=function(food){ document.writeln(this.name); } ; function child (name,age){ Person.apply(this,arguments), this.age=age } child.prototype.fly= function(where){ document.writeln(where); } ; var a = new child("pc",12); a.fly(" house") ; a.eat("sweet ")
运行后 只会输出 house
所以使用apply来实现的时候要注意方法写在Person里面
2)使用apply的arg写出优雅的代码 如
1.
var a = Math.min(1,3,7,2,8,8); document.writeln(a); //1
但是如果我要求出一个数组的的min呢 难道要写循环? apply 帮您解决
var a = [1,3,7,2,8,8] ; var b=Math.min.apply(null,a) ; document.writeln(b); //1
2.
var arr1=[1,2,3]; var arr2 = [4,5,6] ; arr1.push(arr2); console.log(arr1);
这样就会出现 [1,2,3,[4,5,6]] apply也可以解决
var arr1=[1,2,3]; var arr2 = [4,5,6] ; arr1.push.apply(arr1,arr2); console.log(arr1);//[1,2,3,4,5,6]
也可以这样写
var arr1=[1,2,3]; var arr2 = [4,5,6] ; Array.prototype.push.apply(arr1,arr2) console.log(arr1);<span style="font-family: Arial, Helvetica, sans-serif;">//[1,2,3,4,5,6]</span>
0 0
- 【javascript】 function.apply 菜鸟学习笔记
- Javascript学习笔记: Function::apply 方法
- JavaScript call() apply()学习笔记
- 前端call 和apply(javascript学习笔记)
- javascript学习笔记之Call()和Apply()
- JavaScript学习笔记之Apply和Call
- javascript学习笔记之apply()和call()
- 菜鸟的javascript学习笔记
- JavaScript学习笔记(二):Function
- 菜鸟学习笔记——function(index,value)的困扰
- JavaScript之Function的apply与call
- [Javascript Function] Arguments, call(), apply(), caller(), callee()
- 【javascript】 array.reduce 菜鸟学习笔记
- 【javascript】 object.__proto__ 菜鸟学习笔记
- 【javascript】ES6 特性 菜鸟学习笔记
- JavaScript基础学习笔记(菜鸟必看篇)
- [Javascript]菜鸟的Dojo学习笔记1
- JavaScript学习笔记(1)---理解function
- 菜鸟教程之工具使用(九)——Git如何进行分支的merge操作
- COPY 计算几何基础——矢量和叉积
- spring配置定时器的时间设置
- Java序列化与JSON序列化大比拼2(alibaba/fastjson)
- 泛型T的类型获取
- 【javascript】 function.apply 菜鸟学习笔记
- 思考随笔(2014-12-30)
- 关于indexOf
- Openwrt make出现的错误
- BIOS 的 recovery 机制
- Alpha、Beta、RC、GA版本的区别
- WinDbg重建堆栈
- 以Jar形式为Web项目提供资源文件(JS、CSS与图片)
- Zend API 二(重要) (自用备注)