Object.assign 方法不绑定“this”

2024-05-06

我正在尝试绑定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(使用前将#替换为@)

Object.assign 方法不绑定“this” 的相关文章

随机推荐