JavaScript中apply() call() 函数

来源:互联网 发布:手机淘宝直播怎么开通 编辑:程序博客网 时间:2024/04/30 07:49
// 首先理解apply()函数 call() 函数<script type="text/javascript">function Person(name,age){this.name = name;this.age = age;}function Student(name,age,grade){Person.apply(this,arguments);//Person.call(this,name,age);}var student = new Student("ilv",20,"大四");alert(student.name + student.age + student.grade);//ilv20大四//定义:应用某一对象的一个方法,用另一个对象替换当前对象。 //通俗讲就是用student来执行person类里的内容//什么情况下用apply ? 什么情况下用 call//在给对象参数的情况下,如果参数的形式是数组的时候,比如apply//示例里面传递了参数arguments,这个参数是数组类型,并且在调用//Person的时候参数的列表是对应一致的//(也就是Person和Student的参数列表前两位是一致的) 就可以采用 apply , //如果我的Person的参数列表是这样的(age,name),//而Student的参数列表是(name,age,grade),这样就可以用call来实现了,//也就是直接指定参数列表对应值的位置(Person.call(this,age,name,grade));  //http://blog.csdn.net/business122/article/details/8000676 (原文)</script>

原创粉丝点击