js prototype原型链的利与弊

何时使用prototype 已经声明一个方法,你想让所有这个方法的对象实例都能继承这个方法的属性,那你可以使用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 上声明一次,所有实例都可以共享这个属性。 它的缺点是: 当我们查找一个不存在的属性,比如tommy.habit 的时候,浏览器会先按以下顺序查找: tommy tommy. proto tommy.proto.proto tommy.proto.proto.proto 经过四次遍历查询还没有找到,则返回null 显然,这很影响性能。 怎么优化呢? 先判断tommy.hasOwnProperty('habbit'), if true, 继续; else 判断 tommy. proto.hasOwnProperty('habbit'), 如果没有,就不要执行了。

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):

昵称:
邮箱:
内容: