Ember.js how does reopenClass work?

前端 未结 2 981
说谎
说谎 2020-12-24 07:02

I don\'t really get the function of ember.js\' reopenClass. I thought it added extra code to the Object\'s prototype, so all instances of that Object would get the functiona

2条回答
  •  清酒与你
    2020-12-24 08:04

    reopen changes prototype and thus changes instances of a class

    reopenClass changes the constructor itself and thus changes the class by creating static properties and functions that are only available on the class but not on any instances of the class.

    Note that the changes introduced by reopen only take effect after calling .create()

    Code examples based on the doc:

    http://emberjs.com/api/classes/Ember.Application.html#method_reopen

    MyObject = Ember.Object.extend({
      name: 'an object'
    });
    
    o = MyObject.create();
    o.get('name'); // 'an object'
    
    MyObject.reopen({
      say: function(msg){
        console.log(msg);
      }
    })
    
    try{
        o.say("hey");
    } catch(e) {
        console.log(e); // o.say is not a function (...yet)
    }
    o2 = MyObject.create();
    o2.say("hello"); // logs "hello"
    
    o.say("goodbye"); // logs "goodbye"
    

    http://emberjs.com/api/classes/Ember.Application.html#method_reopenClass

    MyObject = Ember.Object.extend({
      name: 'an object'
    });
    
    MyObject.reopenClass({
      canBuild: false
    });
    
    MyObject.canBuild; // false
    o = MyObject.create();
    o.canBuild; // undefined
    

提交回复
热议问题