一个前端QQ群里,有人提问,关于面向对象的……我看完后解答了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function Person(){ this.name = "lxchuan12"; } var rowboat = new Person(); Person.prototype.age=20; Person.prototype={a:1,b:2}; //Person.prototype.constructor = Person; console.log(rowboat.name);//"lxchuan12" console.log(rowboat.age);//20 console.log(rowboat.a);//undefined console.log(rowboat.b);//undefined console.log(rowboat); console.log(Person.prototype.name);//undefined console.log(Person.prototype.age);//undefined console.log(Person.prototype.a);//1 console.log(Person.prototype.b);//2 console.log(Person.prototype.constructor);//function Object() { [native code] } console.log(Person.prototype);//Object {a: 1, b: 2}
|
问题:
他不明白,为什么rowboat.age为20。但Person.prototype.age却为undefined。
解答:
我把代码在jsbin运行后,为之解答。
Person.prototype={a:1,b:2};这种写法是赋值,
与Person.prototype.age=20;写法不同,不经意间把constructor指向原本为Person的,改为了Object(一般来说,需要修正指向。Person.prototype.constructor = Person)。
控制台输出对象
相当于prototype下只有a,b两个值了。所以Person.prototype.age则是undefined。
但rowboat.age是原型上的,可以找到,所以是20。
所谓原型查找:查找的是构造器查找的原型,构造器是指向一个function(){},里面没有a和b.
参考资料:
《JavaScript高级程序设计》——对象学习笔记
小结:
学习js面对对象编程相关知识,对了解js语言很有帮助。另外,有人说,能写组件,做组件开发说明达到了中级水平。
本文地址:
https://lxchuan12.github.io/2016/08/30/20160830-js-oop-prototype-constructor/