js中apply和call方法的应用
2016-01-26 15:28
543 查看
对象的继承,就是: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=[];
for(var key in this){
if(typeof(this[key])!="function"){
msg.push([key,":",this[key]].join(""));
}
}
alert(msg.join(" "));
};
}
function Student(name,age,grade,school){ //学生类
console.log(typeof arguments);
Person.apply(this,arguments);
Print.apply(this,arguments);
this.grade=grade; //年级
this.school=school; //学校
}
var p1=new Person("jake",10);
p1.sayhello(); // hello
var s1=new Student("tom",13,6,"清华小学");
s1.show(); // name:tom age:13 funcName:Print grade:6 school:清华小学
s1.sayhello(); // helo
alert(s1.funcName); // Print
</script>
总结: a.apply(b,["zhou","23"]) // b继承a
a.call(b,arg1,arg2); // b继承a
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=[];
for(var key in this){
if(typeof(this[key])!="function"){
msg.push([key,":",this[key]].join(""));
}
}
alert(msg.join(" "));
};
}
function Student(name,age,grade,school){ //学生类
console.log(typeof arguments);
Person.apply(this,arguments);
Print.apply(this,arguments);
this.grade=grade; //年级
this.school=school; //学校
}
var p1=new Person("jake",10);
p1.sayhello(); // hello
var s1=new Student("tom",13,6,"清华小学");
s1.show(); // name:tom age:13 funcName:Print grade:6 school:清华小学
s1.sayhello(); // helo
alert(s1.funcName); // Print
</script>
总结: a.apply(b,["zhou","23"]) // b继承a
a.call(b,arg1,arg2); // b继承a
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- Python动态类型的学习---引用的理解
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法
- Redux系列02:一个炒鸡简单的react+redux例子
- JavaScript 各种遍历方式详解
- call/apply/bind 的理解与实例分享
- 如何创建对象以及jQuery中创建对象的方式