// 原型繼承
function Person(name,age){
this.name=name;
this.age=age;
}
// 利用原型中的成員可以被和其他相關的對象共享這一特性,可以實現繼承
Person.prototype.sayHello=function(){
console.log("我想死你了");
}
// 1 給原型對象中添加成員(通過對象的動態特性) 不是嚴格意義上的繼承
var p=new Person("馮鞏",50);
p.sayHello();
// p對象就繼承了原型對象
// 2 直接替換原型對象。 會將原有原型中的成員丟失
var parent={
sayHello2:function(){
console.log("hello")
}
}
Person.prototype=parent;
var p2=new Person("趙本山",60);
p2.sayHello2();
// p2.sayHello(); 會將原有原型中的成員丟失 p2.sayHello is not a function
// p對象繼承了原型對象(parent)
// 3 利用混入的方法給原型對象添加成員
var grandP={
SayBey:function(){
console.log("bye")
}
}
for(var k in grandP){
Person.prototype[k]=grandP[k]
}
var p3=new Person("白雲","44")
p3.SayBey();
// 也是實現了繼承
// 繼承的方法
let arr1 =[1,2,3];
Array.prototype.sayHello=function(){
console.log("hello")
}
console.log(arr1);
arr1.sayHello();
// 擴展內置對象 (給內置對象新增成員);
// 不推薦 系統共享 會修改他人的內置對象
// 安全的擴展一個內置對象
function MyArray(){
}
var arr23=new Array(); // 創建數組
MyArray.prototype=arr23; // 添加內置對象
var myArray=new MyArray; // 繼承自arr23
myArray.push(1);
console.log(myArray); // 1
var arr2 = {
arr2Say:function(){
console.log("我是arr2");
}
}
MyArray.prototype=arr2; // 添加say方法 就自己調用自己的方法
var ArrSay=new MyArray; // 創建構造函數
ArrSay.arr2Say();
var guodegang={
xiangsheng:function(){
console.log("我來將相聲了");
}
}
MyArray.prototype=guodegang;
var guoqiling=new MyArray;
guoqiling.xiangsheng();
// 繼承的方法2
function Animail(){
this.gender="male";
}
Human.prototype=new Animail();
Human.prototype.constructor=Human;
function Human(){
this.actionWay="走路";
}
Teacher.prototype=new Human();
Teacher.prototype.constructor=Teacher;
function Teacher(){
this.skill="教書";
}
BadTeacher.prototype=new Teacher();
BadTeacher.prototype.constructor=BadTeacher;
function BadTeacher(){
this.name="呂超";
}
var t=new BadTeacher();
// 控制檯 t.__proto__ 繼承的應用