2016-05-26 4 views
0

У меня есть базовый объект ProfileDialog, который я распространяю с Object.assign().Object.assign() глубокий объект

var ProfileDialog = function (containerObj) { 
    this.init = function() { 
     this.container = containerObj; 
    }; 

    this.render = function() { 
     let content = document.createElement('div'); 
     content.innerText = 'Dialog here'; 
     this.container.appendChild(content); 
    }; 

    this.init(); 
    this.render(); 
}; 

Mixin:

var DialogMixin = function() { 
    return { 
     open: function() { 
      this.container.style.display = 'block'; 
     }, 
     close: function() { 
      this.container.style.display = 'none'; 
     } 

    } 
}; 

Теперь я выполнить задание:

Object.assign (ProfileDialog.prototype, DialogMixin());

Это работает просто отлично, this контекст разрешает штраф в open и close методов.

Но, когда я поставил подмешать в более глубокой структуре, помещая его в actions собственности:

var DialogMixin = function() { 
    return { 
     actions: { 
      open: function() { 
       this.container.style.display = 'block'; 
      }, 
      close: function() { 
       this.container.style.display = 'none'; 
      } 
     } 
    } 
}; 

контекст становится объектом actions так кодовыми перерывов.

Как правильно расширить объект новыми методами, когда они будут помещены в глубокую структуру?

+0

Это неправильный синтаксис JavaScript. –

+0

Правеен, что с ним? –

+0

Нет ... Я не говорил о 'let' или' var'. Вы используете 'babel.js'? –

ответ

0

Единственное, что я могу придумать, это использовать bind для привязки this.

Так что-то вроде

var ProfileDialog = function (containerObj) { 
    this.containerObj = containerObj; 
}; 

var DialogMixin = function (newThis) { 
    var obj = { 
     actions: { 
      open: function() { 
       console.log('open', this, this.containerObj.style); 
      } 
     } 
    } 
    obj.actions.open = obj.actions.open.bind(newThis); 
    return obj; 
}; 

var container = { 
    style : 'some style' 
}; 
var dialog = new ProfileDialog(container); 
var mixinDialog = Object.assign(dialog, DialogMixin(dialog)); 

mixinDialog.actions.open(); 

См https://jsfiddle.net/zqt1me9d/4/

Смежные вопросы