gpt4 book ai didi

javascript - 自引用嵌套对象

转载 作者:行者123 更新时间:2023-12-03 02:33:39 25 4
gpt4 key购买 nike

亲爱的 JavaScript 大师。

我了解了数十篇有关范围、对象、this 关键字等的文章
但这些仅显示了基本示例。
我看到的大部分代码都是又长又乱的 JavaScript。

我想实现行为,其中每个对象中的“this”引用对象本身。
此测试片段具有所需的行为。

问题:
有没有更好的方法来实现这一目标?
这不是反模式吗?

var mainObject = {};
mainObject.childObject = {};

/* CHILD OBJECT
*/
(function() {

function childObject(){
this.property = 'childObject';
this.childMethod = function(){
console.log( 'child obj method' );
};
}
return childObject;

})().apply(mainObject.childObject);


/* MAIN OBJECT
*/
(function() {

function mainObject(){
this.property = 'mainObject';
console.log( 'main obj method' );
this.childObject.childMethod();
}
return mainObject;

})().apply(mainObject);



console.log( mainObject );
console.log( mainObject.childObject );

最佳答案

不确定它本身是否符合“反模式”的资格,但肯定有很多不必要的事情发生。这是一个简化的示例,维护您声明的静态函数:

var mainObject = {};
mainObject.childObject = {};

function modifyChild() {
this.property = 'childObject';
this.childMethod = function() {
console.log('child obj method');
};
}

modifyChild.call(mainObject.childObject);

function modifyMain() {
this.property = 'mainObject';
console.log('main obj method');
this.childObject.childMethod();
}

modifyMain.call(mainObject);

console.log(mainObject);
console.log(mainObject.childObject);

一般来说,如果您想要一个静态函数,您可以直接调用,无需链接 .call().apply(),并传入 这个上下文,你可以.call.bind()它自身:

var someFunction = (function () {
function someFunction () {
console.log(this);
}

return someFunction.call.bind(someFunction);
})()

someFunction({ foo: 'bar' });

关于javascript - 自引用嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48625940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com