構(gòu)造函數(shù)
類似于類的概念 約定俗成 首字母大寫
-
簡單舉個例子:
function Dog(name, age, sex) { this.name = name; this.age = age; this.sex = sex; this.action = function() { console.log("吃 撒歡 叫"); } } //調(diào)用構(gòu)造函數(shù) //實例化 關(guān)鍵字 new(把抽象類具體化,把類變成對象) var ahuang = new Dog("阿黃", "2", "母"); var dahei = new Dog("大黑", "2", "母"); var abiao = new Dog("阿??", "2", "母"); ahuang.action() console.log(abiao);
E0D5C827-5D5E-44A2-BA81-74471441EE77.png
-
new在構(gòu)造函數(shù)中做了什么?
1.創(chuàng)建了一個空的對象var obj = {}
2.改變了this指向:call apply bind
Car.call(obj, "w6", "red");
傳參:
apply:接收數(shù)組
call:接收字符串
3.賦值原型:
obj.__proto__ = Car.prototype;
對象是由自身和原型共同構(gòu)成的 對象的原型:proto
構(gòu)造函數(shù)是由自身和原型共同構(gòu)成的 構(gòu)造函數(shù)的原型:prototype
屬性寫在構(gòu)造函數(shù)里面,方法寫在原型上
constructor找到函數(shù)本身
console.log(Person.prototype.constructor)
-
類的特征:封裝 繼承 多態(tài) 重載
封裝 公有,私有屬性function Person(name){ //私有屬性 var name=name; //公有屬性 this.height="195cm"; this.get=function(){ // get 通過共有方法訪問私有屬性 return name; } //set方法 設(shè)置私有屬性 this.set=function(newname){ name=newname; console.log(newname); } } var newPerson=new Person("張三"); console.log(newPerson.get()) console.log(newPerson.set("李四"))
C3A46A1F-7ED6-4EF6-81C6-318773B40BBA.png
分析結(jié)果:首先get是通過公用屬性訪問私有屬性可以訪問到,而set與其相反也就訪問不到數(shù)據(jù),只有內(nèi)部自身能訪問到
繼承
function Person(sex, height) {
this.sex = sex;
this.height = height;
// this.hobby=function(){
// console.log("吃苦耐勞")
// }
}
Person.prototype.hobby = function() {
console.log("我是人類")
}
function Student(sex) {
//Person.call(this,sex);
Person.apply(this, [sex]);
//Person.bind(this)(sex);
this.action = function() {
console.log("貪玩");
}
}
//涉及到傳址的問題
//Student.prototype=Person.prototype
//重新寫子集的方法也會影響到父級
// 解決傳址問題
function Link() {};
Link.prototype = Person.prototype;
Student.prototype = new Link();
console.log(Student.prototype);
// Student.prototype.hobby = function() {
// console.log("我是")
// }
// var newStudent=new Student("男");
var newStudent = new Student("男");
//var newStudent=new Student("男");
console.log(newStudent.sex);
newStudent.hobby();
newStudent.action();
var newPerson = new Person("男", "182cm");
console.log(newPerson)
newPerson.hobby()
使用call apply bind方法繼承只能繼承其屬性并不能繼承其原型,所以要繼承其原型我們還要另想它法,如果我們使用Student.prototype=Person.prototype這種樣式來設(shè)置的話,這就會涉及傳址問題,所以這種方式并不可取,所以最簡單有效的方法就是新創(chuàng)建一個構(gòu)造函數(shù),用來在其中周旋如:function Link() {};Link.prototype = Person.prototype;Student.prototype = new Link();這樣使用的話,不認我們怎么改變newStudent的hobby也不會影響其父級的hobby,這樣我們就結(jié)局了繼承問題。