1. 程式人生 > >構造函數可以實例化對象

構造函數可以實例化對象

體重 直接 study pro 代碼 dog lee struct type

 構造函數可以實例化對象
* 構造函數中有一個屬性叫prototype,是構造函數的原型對象
* 構造函數的原型對象(prototype)中有一個constructor構造器,這個構造器指向的就說自己所在的原型對象所在的構造函數
* 實例對象的原型對象(__proto__)指向的是該構造函數額原型對象
* 構造函數的原型對象(prototype)中的方法是可以被實例對象直接訪問的

* 需要共享的數據可以寫在原型中
* 不需要共享的數據可以寫在構造函數中

//構造函數
function Student(name,age,sex) {
this.name=name;
this.age=age;
this.sex=sex;
}
//共享===》所有學生身高188,體重55,每天要敲50行代碼,每天吃10斤西瓜

// //原型對象
// Student.prototype.height="188";
// Student.prototype.weight="55";
// Student.prototype.study=function () {
// console.log("要寫50行代碼");
// };
// Student.prototype.eat=function () {
// console.log("要吃10斤西瓜");
// };

//原型簡單寫法
Student.prototype={
//手動修改構造器的指向
constructor:Student, //========================
height:"188",
weight:"55",
study:function () {
console.log("要寫50行代碼");
},
eat:function () {
console.log("要吃10斤西瓜");
}
};

//實例化對象,並初始化
var stu=new Student("小黑",22,"男");
console.dir(Student);


function Animal(name,age) {
this.name=name;
this.age=age;
}
//原型中添加方法
Animal.prototype.eat=function () {
console.log("喜歡吃水果");
this.play();
};
Animal.prototype.play=function () {
console.log("喜歡玩蕩秋千");
this.sleep();
};
Animal.prototype.sleep=function () {
console.log("睡著了");
};
var dog=new Animal("小明",6);
dog.eat();

構造函數可以實例化對象