這只是更新類的實現(xiàn),而不重新定義它。這是必要的,只有當(dāng)你不想擴展內(nèi)置類,但更新其實現(xiàn)。這可以通過使用以下方法:
reopen():此方法通常會將屬性和方法添加到實例。
reopenClass():方法會將屬性和方法添加到類。
var Person = Ember.Object.extend({ firstName: null, lastName: null }); Person.reopen({ middleName: 'Smith' }); var Person = Ember.Object.extend({ firstName: null, lastName: null }); Person.reopenClass({ createMan: function() { return Person.create({isMan: true}) } });
上面的代碼描述了如何重新打開類Person,將變量名稱middleName添加到實例,并使用reopenClass為Person類添加createMan函數(shù)。
<!DOCTYPE html> <html> <head> <title>Emberjs Reopening Classes and Instances</title> <!-- CDN's--> <script src="/attachements/w3c/handlebars.min.js"></script> <script src="/attachements/w3c/jquery-2.1.3.min.js"></script> <script src="/attachements/w3c/ember.min.js"></script> <script src="/attachements/w3c/ember-template-compiler.js"></script> <script src="/attachements/w3c/ember.debug.js"></script> <script src="/attachements/w3c/ember-data.js"></script> </head> <body> <script type="text/javascript"> //reopen() method for instances var Person = Ember.Object.extend({ firstName: null, lastName: null, }); //adding new variable to the Person class Person.reopen({ middleName: 'Smith', }); document.write('Middle Name: '+Person.create().get('middleName')); //reopenClass() method for classes var Person = Ember.Object.extend({ firstName: null, lastName: null, }); Person.reopenClass({ //creating new method for class Person createMan: function() { return Person.create({isMan: true}) } }); document.write('isMan: '+Person.createMan().get('isMan')); </script> </body> </html>
讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:
將以上代碼保存在 reopncls_inst.html 文件中
在瀏覽器中打開此HTML文件。
更多建議: