javascript 中 apply(或call)方法的用途----对象的继承

时间:2021-07-12 22:41:53

一直以来,我的理解就是  js中的Function.apply(或者是Function.call)方法是来改变Function 这个函数的执行上下文(excute Context),说白了,就是改变执行时函数所处的作用域,

最直接的就是影响到 this 这个预定义的变量的值。!!Function.apply(obj, arguments),就是改变 function 的执行环境为 传入的obj 对象,即 Funtion 内部的this 会被改变为 obj.

下面的这个例子是搜索别人的例子的。

先看个例子

function Person(name,age,grade){   //定义一个类,人类
this.name=name; //名字
this.age=age; //年龄
this.sayhello=function(){alert(grade)};
}
function Student(name,age,grade,school){ //学生类
Person.apply(this,arguments);
for(var i in arguments){alert(arguments[i])} this.grade=grade; //年级
this.school=school; //学校
}
stu = new Student('yuanshao',26,'university','Huaqiao')
stu.sayhello();//这样stu就有了 Person构造器中的sayhello()方法。

  解释一下:

apply方法能劫持另外一个对象的方法,继承另外一个对象的属性

Function.apply(obj,args)方法能接收两个参数

obj:这个对象将代替Function类里this对象

args:这个是数组,它将作为参数传给Function(args-->arguments)

再看个例子:

alert(Math.max(5,8,9,11))   //8 可以
————————————
var arr=[5,7,9,1]
alert(Math.max(arr)) // 这样却是不行的。
——————————————————————
var arr=[5,7,9,1]
alert(Math.max.apply(null,arr)) // 这样却行的。一定要这样写