1-1 call实现属性继承
function Person(name,age){
this.name = name;
this.age = age;
}
function Teacher(name,age,skill){
var self = this;
Person.call(self,name,age)
this.skill = skill;
}
var t = new Teacher("zhang",18,"js");
console.log(t)
function Person(name,age){
this.name = name;
this.age = age;
}
function Teacher(name,age,skill){
Person.call(this,name,age)
this.skill = skill;
}
var t = new Teacher("zhang",18,"js");
console.log(t)
1-2 方法的继承
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
function Student(name,age,skill){
Person.call(this,name,age);
this.skill=skill;
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
var s = new Student("cheng",18,"js");
console.log(s.constructor == Student)
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
function Student(name,age,skill){
Person.call(this,name,age);
this.skill=skill;
}
Student.prototype = Person.prototype;
Student.prototype.constructor = Student;
Student.prototype.sayAge = function(){
console.log(this.age)
}
var s = new Student("cheng",18,"js");
console.log(s.constructor == Student)
1-3 Object.create实现继承
如果想创建一个继承自其他对象的对象,可以使用Object.create()指定[[Prototype]]为一个新的对象。
function Person(){
}
Person.prototype.sayName = function(){
console.log("name")
}
function Teacher(){
}
Teacher.prototype = Object.create(Person.prototype,{
constructor:{
value:Teacher
}
});
var t = new Teacher();
var p = new Person();
console.log(t);