JavaScript 继承(原型链 构造 实例 组合)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JavaScript 继承(原型链 构造 实例 组合),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2565字,纯文字阅读大概需要4分钟。
内容图文
![JavaScript 继承(原型链 构造 实例 组合)](/upload/InfoBanner/zyjiaocheng/715/aeb5211ca5ed46f19c6d8812a355221e.jpg)
实例化对象
function Animal(){
this.name=null;
this.sleep=function(){
return "睡觉";
};
this.eat=function(){
return "吃";
}
}
var animal=new Animal();
console.log(animal);
//原型链继承 _proto_
function Dog(){
this.type="犬";
}
Dog.prototype=new Animal();
Dog.prototype.color="red"; //想为子类添加属性要放在原型链继承之后进行 否则会被覆盖
var dog=new Dog();
console.log(dog); //dog将继承Animal的属性
console.log(typeof dog); //object
console.log(dog instanceof Dog); //检测dog的实例对象是不是Dog 是的话返回true
console.log(dog instanceof Animal); //true
原型链继承 单继承 实例是子类的实例也是父类的实例。
在数组上封装一个方法去调用执行 进行数组的排序
Array.prototype.mySort=function(){
}
var a=[1,3,2,9,8];
a.mySort();
构造继承 call apply 对象指针的替换。 子类的实例是自身 而不是父类。_proto_为object。 call有多个参数,apply有两个参数。 构造继承不能继承父类的原型方法和属性,不能追加。只继承父类现有的方法。Student.prototype.work=function(){return this.name+"跑步"}
无效。
function People(){
this.sex=null;
this.eat=function(){
return "吃";
}
}
function children(){
People.call(this); // People.apply(this);
}
var child=new children();
console.log(child);
console.log(child instanceof children); //true
console.log(child instanceof People); //false
构造继承 多继承
//构造继承传参
function people(){
this.name=arguments[0];
this.sex=arguments[1];
this.eat=function(){
return this.name+"正在吃饭";
}
}
function Student(){
this.score=arguments[0];
this.wirtezuoye=function(){
return this.name+"写作业";
}
}
function children(name,sex,score){
people.call(this,name,sex);
//people.apply(this,[name,sex]); apply方法
Student.call(this,score);
}
var child=new children("花生","男",99);
console.log(child);
console.log(child.eat()); //花生在吃饭
console.log(child.writezuoye()); //花生在写作业
实例继承
new对象返回对象。子类的实例不是自身是父类,不能多继承。
function f1(){
this.name=null;
this.sleep=function(){
return "睡觉";
}
}
function f2(){
var f=new f1();
return f;
}
var fchild=new f2();
console.log(fchild);
console.log(fchild instanceof f2); //false 实例不是自身
console.log(fchild instanceof f1); //true 实例是父类
组合继承
弥补原型链继承和构造继承的缺点。既是子类的实例又是父类的实例。
function mutou(){
this.name=arguments[0];
this.mack=function(){
return "制作"+this.name;
}
}
function bandeng(name){
mutou.call(this,name);
}
bandeng.prototype=new mutou(); //利用原型链
var ban=new bandeng("板凳");
console.log(ban);
console.log(ban.mack());
console.log(ban instanceof bandeng); //true
console.log(ban instanceof mutou); //false 添加bandeng.prototype=new mutou();之后变为true
内容总结
以上是互联网集市为您收集整理的JavaScript 继承(原型链 构造 实例 组合)全部内容,希望文章能够帮你解决JavaScript 继承(原型链 构造 实例 组合)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。