我正在尝试绑定this
变量到一个新对象。
function Parent(){
//sub-component constructors
this.components={
node:function(){
this.name = 'jordan';
}
},
//subcomponent methods
this.ctrl={
nodes:{
type1:{
test1:function(){
console.log('firing');
console.log(this);
//return undefined should return 'jordan'
console.log(this.name);
},
test2:function(){
console.log(this);
}
}
}
}
};
//INIT
function init(){
//CREATE NEW
var parent = new Parent();
var props = {
"ctrl": parent.ctrl.nodes.type1
};
//OBJECT ASSIGN
var node = Object.assign(new parent.components.node(),props);
console.log(node);
//WHY ISN'T THE (THIS) VARIABLE SET WHEN I CALL
node.ctrl.test1();
}
//EXECUTE INIT
document.addEventListener('DOMContentLoaded',init);
问题:为什么不是this
变量设置自Object.assign()
当我打电话时node.ctrl.test1()
which console.log(this.name)
?
看看下面的定义Object.assign
:
Object.assign(target, ...sources)
这意味着Object.assign(parent.components.node,props)
分配props
反对parent.components.node
,覆盖之前分配给它的函数。
Calling node.ctrl.test1()
工作方式与您尝试调用的方式相同props.ctrl.test1()
,这显然行不通。
new parent.components.node()
也不会工作,因为你将分配props
到使用返回的对象node
作为构造函数。该对象只会有一个name
财产。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)