在介紹prototype原型對(duì)象之前,先了解一下靜態(tài)成員和實(shí)例成員是什么:
-
靜態(tài)成員和實(shí)例成員
- 使用構(gòu)造函數(shù)方法創(chuàng)建對(duì)象時(shí)互亮,可以給構(gòu)造函數(shù)和創(chuàng)建的實(shí)例對(duì)象添加屬性和方法惕艳,這些屬性和方法都叫做成員乐设。
function Student(name,id){
this.name = name;
this.id = id;
this.message = function(){
console.log(this.name + "," + this.id);
};
}
//生成對(duì)象實(shí)例
var student5 = new Student("ls",789);
//調(diào)用方法
student5.message();
- 實(shí)例成員:在構(gòu)造函數(shù)內(nèi)部添加給 this 的成員晚树,屬于實(shí)例對(duì)象的成員,在創(chuàng)建實(shí)例對(duì)象后必須由實(shí)例對(duì)象調(diào)用崇堵,構(gòu)造函數(shù)是不能調(diào)用的型诚。
console.log(student5.id);
console.log(Student.id);
- 靜態(tài)成員:是直接添加給構(gòu)造函數(shù)自身的成員,只能使用構(gòu)造函數(shù)調(diào)用鸳劳,不能使用生成的實(shí)例對(duì)象調(diào)用狰贯。
Student.version = "1.0";
console.log(student5.version);
console.log(Student.version);
prototype 原型對(duì)象
function Student(name,id){
this.name = name;
this.id = id;
}
//獲取對(duì)象的prototype
Student.prototype.type = "student";
Student.prototype.message = function(){
console.log(this.name + "," + this.id);
};
prototype屬性值是一個(gè)對(duì)象,通常叫做原型對(duì)象
對(duì)象內(nèi)部可以添加一些屬性和方法
構(gòu)造函數(shù)的原型對(duì)象上都默認(rèn)有一個(gè)constructor屬性棍辕,指向prototype對(duì)象所在函數(shù)
所有的對(duì)象都有一個(gè)
__proto__
的屬性暮现,是一個(gè)指針还绘,指向的是生成實(shí)例對(duì)象的構(gòu)造函數(shù)的原型對(duì)象楚昭。_proto_
屬性并不是一個(gè)標(biāo)準(zhǔn)屬性,是瀏覽器自己根據(jù)語法自己生成的(實(shí)際開發(fā)中拍顷,不會(huì)寫__proto__
的抚太,實(shí)例直接訪問對(duì)象成員)
image.png