javascript apply
apply 方法很强大,可以用来实现类似面向对象编程的特性。
实现继承:
function Person(){
this.a = 'person';
this.b = function(){
alert('I\'m a person!');
}
}
function Student(){
Person.apply(this,arguments);
this.a = 'student';
this.c = 'Student class';
this.b = function(){
alert('I\'m a Student');
}
this.d = function(){
alert('This is Student\'s function.');
}
}
function main(){
var student = new Student();
student.b();
alert(student.a);
alert(student.c);
student.d();
}
main();
注意,如果在Student()中,将
Person.apply(this,arguments);
移到函数尾,则结果大不一样,象这样:
function Student(){ this.a = 'student'; this.c = 'Student class'; this.b = function(){ alert('I\'m a Student'); } this.d = function(){ alert('This is Student\'s function.'); }
Person.apply(this,arguments); }
Person 中的属性和方法会覆盖掉Student的属性和方法。
说明,下面的参考文章关于数组的push.apply()验证
arr1.push(arr2)显然是不行的。 因为这样做会得到[1,3,4,[3,4,5]]
Array.prototype.push.apply(arr1,arr2) 结果:arr1=[1,3,4,3,4,5]
var arr1=[1,3,4]; var arr2=[3,4,5]; function test1(obj){ var arrLen=arr2.length; for(var i=0;i<arrLen;i++){ arr1.push(arr2[i]); } } function main(){ //test1(); //Array.prototype.push.apply(arr1,arr2); //arr1.push(arr2); for(var i=0;i<arr1.length;i++){ alert(i + '=' + arr1[i]); } alert(arr1.join(',')); }
参考文章:
js中apply方法的使用
1、对象的继承,一般的做法是复制:Object.extend
prototype.js的实现方式是:
Object.extend = function(destination, source) {
for (property in source) {
destination[property] = source[property];
}
return destination;
}
除此之外,还有种方法,就是:Function.apply(当然使用Function.call也是可以的)
apply方法能劫持另外一个对象的方法,继承另外一个对象的属性
Function.apply(obj,args)方法能接收两个参数
obj:这个对象将代替Function类里this对象
args:这个是数组,它将作为参数传给Function(args-->arguments) apply示范代码如下:
<script>
function Person(name,age){//定义一个类,人类
this.name=name; //名字
this.age=age; //年龄
this.sayhello=function(){alert("hello")};
}
function Print(){//显示类的属性
this.funcName="Print";
this.show=function(){
var msg=[];