JS高級---建構式,通過原型添加方法,原型的作用: 共享資料, 節省記憶體空間
建構式
//建構式 function Person(sex, age) { this.sex = sex; this.age = age; }
通過原型添加方法
//通過原型添加方法 Person.prototype.sayHi = function () { console.log("打招呼,您好"); };
通過console.dir來觀察和對比per和Person,可以看出:

實體物件中有個屬性,__proto__,也是物件, 叫原型, 不是標準的屬性, 瀏覽器使用的
console.dir(per);//實體物件 Person

建構式中有一個屬性, prototype, 也是物件, 叫原型, 是標準屬性, 程式員使用
console.dir(Person);//建構式的名字 f Person(sex, age)

因此:
原型---->__proto__或者是prototype, 都是原型物件原型的作用: 共享資料, 節省記憶體空間
var per = new Person("男", 20); console.dir(per);//實體物件 Person console.dir(Person);//建構式的名字 f Person(sex, age) var per2 = new Person("女", 30); console.log(per.sayHi == per2.sayHi); //true
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/159531.html
標籤:JavaScript
下一篇:這么多陣列方法,你掌握了么?
