類的創建和繼承
類的創建,new 一個function ,在這個function的prototype裏面增加屬性和方法。
function A(food){
}
A.prototype.eat=function(food){
}
原型繼承:
Student.prototype=new Person();
Student.prototype.constructor=Student;
缺點:無法設置構造函數的參數
借用構造函數繼承:
function fn(x,y){
console.log(this);
console.log(x+y);
}
var o={
name:'zs'
};
//bind方法 改變函數的this 並且返回一個新的函數 不調用函數
var f=fn.bind(o,1,2);
f();
//call函數 改變函數中的this 直接調用函數
fn.call(o.2.3);
function Person(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
function Student(name,age,sex,score){
Person.call(this,name,age,sex);//改變person的this 使其變成student
this.score=score;
}
var s1=new Student('zs',13,'男',100);
console.dir(s1);
缺點:只可繼承屬性,不能繼承方法。
組合繼承:
繼承方法與屬性綜合:
綜合call方法和
Student.prototype=Person.prototype;
Student.prototype.constructor=Student;
但只有一個對象指向,即student增加一個方法,person也增加一個同樣的方法。若想子類型只有某個方法而父類型沒有,則結合以下:
Student.prototype=new Person();
Student.prototype.constructor=Student;