Jsのプロトタイプチェーンの継承、構造関数の継承、組合せの継承
2218 ワード
昨日はjsのこの三つの継承を勉強しましたが、面接ではやはり聞かれると思います.今朝はまとめました.コードに書いてあります.
// -----------------------------------------
// 1: , 。
// 2: , ;
function Dad(name,age){
this.name = name;
this.age = age;
this.counts = [1,2,3,4,5];
}
Dad.prototype.sayNmae = function() {
console.log(this.name)
};
function Son(name,age){
this.name = name;
this.age = age;
};
Son.prototype = new Dad();
var son = new Son(' ',23);
var dad = new Dad(' ',88);
son.sayNmae();
son.counts.push(6) // counts
var son1 = new Son(' ',11);
console.log(son1.counts)// counts , 1
console.log(son.counts)
console.log(son instanceof Dad);
console.log(dad instanceof Dad);
console.log(dad instanceof Son);
// ,isPrototypeOf() true, .
console.log(Object.prototype.isPrototypeOf(son));
console.log(Dad.prototype.isPrototypeOf(son));
console.log(Son.prototype.isPrototypeOf(son));
// ----------------------------------------- 。
// : .
// 1. , ;
// 2.
// 1. , 。
// 2. 。
function Person(name,age){
this.name = name;
this.age = age;
this.counts = [1,2,3,4,5];
}
function Man(name,age,sex){
Person.call(this,name,age);
this.sex = sex;
}
var man = new Man(' ',18,' ');
var man1 = new Man(' ',19,' ')
man.counts.push(6)
console.log(man);//counts 1 6
console.log(man1);//counts 1 5
// -------------------------------------------
// 1. , , JavaScript . , instanceof isPrototypeOf( ) .
// 1. ,
function Teacher(name,age){
this.name = name;
this.age = age;
}
Teacher.prototype.sayNmae = function(){
console.log(this.name)
}
function Student(name,age,sex){
Teacher.call(this,name,age);
this.sex = sex;
}
Student.prototype = new Teacher();
var student = new Student('liuchanh',18,'boy');
student.__proto__.name = ' ';
console.log(student)