浏览 2571 次
锁定老帖子 主题:纠错 JavaScript 的几个 tip
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-03-06
引用 1、JavaScript 中的继承
在 JavaScript 中实现继承的方法是:将子类的 prototype 属性设置为父类的对象。 例如,我有一个 Basket 类,继承 Hashtable 类: Java代码 1.Basket.prototype = new Hashtable();; 2.Basket.prototype.constructor = Basket; Basket.prototype = new Hashtable();; Basket.prototype.constructor = Basket; 如果不写上面第二句,以后 typeof 一个 Basket 的对象获得的就是 Hashtable 了。 最后一句是错误的, 请看我的测试: <html> <head> </head> <body> <div id='display'></div> <script language="javascript"> function Person(name){ this.name = name; } function Man(){ } var me = new Man(); dwr('me.constructor before change prototype:'+me.constructor); dwr('typeof me before change prototype:'+typeof me); Man.prototype = new Person(); dwr('me.constructor after change prototype:'+me.constructor); dwr('typeof me after change prototype:'+typeof me); var you = new Man(); dwr('create you and you.constructor after change prototype:'+you.constructor); dwr('create you and typeof you after change prototype:'+typeof you); function dwr(s){ var display = document.getElementById('display'); display.innerHTML+=s+'<br/>'; } </script> </body> </html> 运行结果: me.constructor before change prototype:function Man(){ } typeof me before change prototype:object me.constructor after change prototype:function Man(){ } typeof me after change prototype:object create you and you.constructor after change prototype:function Person(name){ this.name = name; } create you and typeof you after change prototype:object 结论: 改变函数的prototype对象并不影响typeof的结果,只影响obj.constructor的结果。 obj.constructor, 该constructor属性是属于该函数的prototype对象的, 或者这么说, 当你创建一个函数Person时, 该函数就会有一个prototype对象, 该prototype对象中持有一个constructor属性来指向这个函数, 所以当你创建这个函数的对象obj后, 有这样的关系: obj.constructor = Person.prototype.constructor = Person 但是当改变函数的prototype对象后: var person = new Person(); Man.prototype = person; var other = new Man(); 那么: other.constructor == Man.prototype.constructor; Man.prototype此时是Person的实例, 即 Man.prototype == person; 所以有: other.constructor == Man.prototype.constructor == person.constructor == Person.prototype.constructor == Person 以下又是测试:) <html> <head> </head> <body> <div id='display'></div> <script language="javascript"> function Person(){}; function Man(){}; var person = new Person(); Man.prototype = person; var other = new Man(); dwr(other.constructor == Man.prototype.constructor); dwr(Man.prototype.constructor == person.constructor); dwr(person.constructor == Person.prototype.constructor); dwr(Person.prototype.constructor == Person); dwr(other.constructor == Person); function dwr(s){ var display = document.getElementById('display'); display.innerHTML+=s+'<br/>'; } </script> </body> </html> 结果: true true true true true 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2011-03-09
沙发,学习一下,好文章
|
|
返回顶楼 | |