何时使用 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'), 如果没有, 就不要执行了.
来源: http://www.jianshu.com/p/420b0c5f0da4