什么是原型箫章?
顧名思義倒庵,原型字面理解就是原來的類型或模型耘纱,這里可以理解為最初的函數(shù)模板.
對(duì)于有基于類的語言經(jīng)驗(yàn) (如 Java 或 C++)的開發(fā)人員來說扣猫,JavaScript有點(diǎn)令
人困惑,因?yàn)樗莿?dòng)態(tài)的捅膘,并且本身不提供一個(gè)class實(shí)現(xiàn)添祸。(在 ES2015/ES6 中引
入了class關(guān)鍵字,但只是語法糖寻仗,JavaScript 仍然是基于原型的[prototype])膝捞。
1、JavaScript中所有的對(duì)象都是Object的實(shí)例愧沟,函數(shù)也是對(duì)象
Object.prototype
console.log(Object.prototype.constructor===Object);//true
console.log(Object.prototype.__proto===null);//true
typeof Object.prototype.__proto //'object'
Foo.prototype
console.log(Foo.prototype.constructor?===Foo);//true
function Foo(){}
const? f =new Foo;
f.__proto__//內(nèi)部原型屬性
console.log(Foo.prototype===f.__proto__);//true
為什么用原型蔬咬?
原型為了實(shí)現(xiàn)面向?qū)ο笏枷搿痉庋b、繼承沐寺、多態(tài)】林艘,繼承原型對(duì)象,實(shí)現(xiàn)多態(tài)
例如:層層繼承
function Person(){}
Person.prototype.getName='zhangsan';
Person.prototype.Age='22';
var Animal=function(){}
Animal.prototype=new Person();
Animal.prototype.address='南京'
Animal.prototype.Age='30';
var temp=new Animal;
console.log(temp.getName);//zhangsan
console.log(temp.address);//南京
console.log(temp.Age);//30