構(gòu)造函數(shù)
約定俗成:首字母大寫(xiě);
function Dog(name,sex){
this.name = name;
this.sex = sex;
this.action = function(){
console.log("吃、叫、撒歡");
}
}
調(diào)用構(gòu)造函數(shù);
實(shí)例化;關(guān)鍵字:new(把抽象類具體化,把類變成對(duì)象);
var xiaohei = new Dog("小黑","female");
console.log(xiaohei.name);
xiaohei.action();
new 具體做了什么?三件事
1 . 創(chuàng)建另一個(gè)空的對(duì)象
var obj = {};
2 . 改變this指向:call aplly bind
Dog.call(obj,"小黑","female");
console.log(obj);
3 . 賦值原型
obj.__proto__ = Dog.prototype;
構(gòu)造函數(shù)的原型
對(duì)象是由自身和原型共同構(gòu)成的;構(gòu)造函數(shù)的原型prototype,屬性寫(xiě)在構(gòu)造函數(shù)里,方法寫(xiě)在原型上
function Person(name,age,height){
this.name = name;
this.age = age;
this.height = height;
}
Person.prototype.action = function(){
//this指實(shí)例化的對(duì)象 實(shí)例化對(duì)象共用this
console.log(this);
console.log("姓名是:"+this.name);
}
Person.prototype.hobby = function(){
console.log(this);
console.log("喜歡");
}
Person.prototype = function(){
action:function(){
console.log("run");
}
}
var newPerson = new Person("張三",19,"178cm");
prototype和proto對(duì)比,一個(gè)實(shí)例化之前,表現(xiàn)形式不同而已
console.log(Person.prototype === newPerson.__proto__); //true
通過(guò)原型找到構(gòu)造函數(shù) constructor
function Person(name){
this.name = name;
}
console.log(Person.prototype.constructor);
image.png
類
類的特性:封裝 ,繼承,多態(tài),重載
function Person(name){
//私有屬性;作用域
var name = name;
//共有屬性;
this.height = "183cm";
//get方法,通過(guò)共有方法訪問(wèn)私有屬性
this.get = function(){
return name;
}
//set方法:設(shè)置私有屬性
this.set = function(newName){
name = newName;
console.log(name);//李四
}
}
var newPerson = new Person("張三");
console.log(newPerson.get());//張三
newPerson.set("李四");
繼承 call apply bind
function Dad(height){
this.name = "張三";
this.age = 58;
this.height= height;
this.money = "$1000000";
this.hobby = function(){
console.log("喜歡太極");
}
}
function Son(height){
//繼承的三種方法 call apply bind
Dad.call(this,height,money);
// Dad.apply(this,[height,money]);
// Dad.bind(this)(height,money);
this.action = function(){
console.log("wan");
}
}
var newSon = new Son("180cm");
console.log(newSon.height);
newSon.hobby();
newSon.action();
image.png
繼承父類原型,涉及到傳址問(wèn)題,影響父級(jí)
Student.prototype = Person.prototype;
//重寫(xiě)子級(jí)的方法會(huì)影響父級(jí)
Student.prototype.hobby = function(){
console.log("我是重寫(xiě)方法");
}
解決傳值問(wèn)題
function Link(){};
Link.prototype = Person.prototype;
Student.prototype = new Link();
ES6 類
class Person{
//類最開(kāi)始在加載的時(shí)候執(zhí)行
constructor(name,age){
this.name = name;
this.age = age;
}
hobby(){
console.log("喜歡");
}
showName(){
console.log(this.name);
}
}
var zs = new Person("zs",28);
console.log(zs.age);
zs.showName();
//類的繼承
class Student extends Person{
constructor(name,age){
//super傳參,繼承屬性
super(name,age);
}
action(){
console.log("我是action函數(shù)");
}
}
var newStudent = new Student("李四",222);
console.log(newStudent.name);
newStudent.hobby();