C同事问了我这个问题。 使用下列这段代码extend UI5标准的控件。
问题1:为什么new 一个JerryButton时,line 35会触发? var oJerryButton = new JerryButton({ application: oApplication } );
答案: debug extend的实现, 在line 330里把调用extend指定的constructor赋给fnClass
然后在line 352把fnClass赋给fnClass.prototype.constructor. 这样,每次用fnClass这个构造器new新的instance时,constructor指向的function会自动被call到。
为什么把constructor的赋值放到extend function外面,由application自己显式赋值,但是在new的时候却不会被调用到了?
答案: 原因是此时传入的constructor为undefine,因此fnClass也是undefine
所以line 352注入的实际上是line 346动态生成的函数体为fnBaseClass.apply的function,这样当然我们自定义的constructor不会执行了。 如果你非要想在extend外面指定constructor,怎么弄? 只需要这样: