何時使用prototype
已經(jīng)聲明一個方法,你想讓所有這個方法的對象實例都能繼承這個方法的屬性嵌纲,那你可以使用prototype师溅。例如:
function Person (props){
this.age = props.age || 0;
this.name = props.name || 'unnamed';
}
Person.prototype.greeting = function (){
console.log('Hi, this is ' + this.name);
};
const tommy = new Person({name: 'Tommy', age: 3});
tommy.greeting();
顯然,只需要在原型對象prototype 上聲明一次仍稀,所有實例都可以共享這個屬性迹炼。
它的缺點是:
當(dāng)我們查找一個不存在的屬性,比如tommy.habit 的時候颠毙,瀏覽器會先按以下順序查找:
- tommy
- tommy. proto
- tommy.proto.proto
- tommy.proto.proto.proto
經(jīng)過四次遍歷查詢還沒有找到斯入,則返回null
顯然,這很影響性能蛀蜜。
怎么優(yōu)化呢刻两?
先判斷tommy.hasOwnProperty('habbit'), if true, 繼續(xù); else 判斷 tommy. proto.hasOwnProperty('habbit'), 如果沒有滴某,就不要執(zhí)行了磅摹。