構(gòu)造函數(shù)
類似于類的概念 約定俗成 首字母大寫
-
簡(jiǎn)單舉個(gè)例子:
function Dog(name, age, sex) { this.name = name; this.age = age; this.sex = sex; this.action = function() { console.log("吃 撒歡 叫"); } } //調(diào)用構(gòu)造函數(shù) //實(shí)例化 關(guān)鍵字 new(把抽象類具體化,把類變成對(duì)象) var ahuang = new Dog("阿黃", "2", "母"); var dahei = new Dog("大黑", "2", "母"); var abiao = new Dog("阿??", "2", "母"); ahuang.action() console.log(abiao);
-
new在構(gòu)造函數(shù)中做了什么?
1.創(chuàng)建了一個(gè)空的對(duì)象var obj = {}
2.改變了this指向:call apply bind
Car.call(obj, "w6", "red");
傳參:
apply:接收數(shù)組
call:接收字符串
3.賦值原型:
obj.__proto__ = Car.prototype;
對(duì)象是由自身和原型共同構(gòu)成的 對(duì)象的原型: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 通過(guò)共有方法訪問(wèn)私有屬性 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("李四"))
分析結(jié)果:首先get是通過(guò)公用屬性訪問(wèn)私有屬性可以訪問(wèn)到,而set與其相反也就訪問(wèn)不到數(shù)據(jù),只有內(nèi)部自身能訪問(wèn)到
繼承
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("貪玩");
}
}
//涉及到傳址的問(wèn)題
//Student.prototype=Person.prototype
//重新寫子集的方法也會(huì)影響到父級(jí)
// 解決傳址問(wèn)題
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這種樣式來(lái)設(shè)置的話,這就會(huì)涉及傳址問(wèn)題,所以這種方式并不可取,所以最簡(jiǎn)單有效的方法就是新創(chuàng)建一個(gè)構(gòu)造函數(shù),用來(lái)在其中周旋如:function Link() {};Link.prototype = Person.prototype;Student.prototype = new Link();這樣使用的話,不認(rèn)我們?cè)趺锤淖僴ewStudent的hobby也不會(huì)影響其父級(jí)的hobby,這樣我們就結(jié)局了繼承問(wèn)題。