Program Club

자바 스크립트 개체에서 부모의 부모에 액세스

proclub 2021. 1. 10. 17:44
반응형

자바 스크립트 개체에서 부모의 부모에 액세스


같은 것

var life= {
        users : {
             guys : function(){ this.SOMETHING.mameAndDestroy(this.girls); },
             girls : function(){ this.SOMETHING.kiss(this.boys); },
        },
        mameAndDestroy : function(group){ },
        kiss : function(group){ }
};

this.SOMETHING은 내가 상상하는 형식이지만 그렇지 않을 수도 있습니다. 개체의 상위 항목으로 이동하는 것은 무엇입니까?


JavaScript는 기본적으로이 기능을 제공하지 않습니다. 그리고 나는 당신이 이런 유형의 기능을 만들 수 있을지 의심 스럽다. 예를 들면 :

var Bobby = {name: "Bobby"};
var Dad = {name: "Dad", children: [ Bobby ]};
var Mom = {name: "Mom", children: [ Bobby ]};

Bobby는 누구의 것입니까?


나는 단순히 첫 번째 기능을 추가했습니다.

parentThis = this;

subfunction에서 parentThis를 사용하십시오. 왜? JavaScript에서는 객체가 부드럽기 때문입니다. 새 멤버는 간단한 할당을 통해 소프트 객체에 추가 할 수 있습니다 (예 : 클래식 객체가 어려운 Java와는 다릅니다. 하드 객체에 새 멤버를 추가하는 유일한 방법은 새 클래스를 만드는 것입니다) 자세한 내용은 여기를 참조하십시오. http : //www.crockford.com/javascript/inheritance.html

또한 마지막에 물체를 죽이거나 파괴 할 필요가 없습니다. 내가 여기에서 찾은 이유 : http://bytes.com/topic/javascript/answers/152552-javascript-destroy-object

도움이 되었기를 바랍니다


이 경우 life부모 개체를 참조하는 데 사용할 수 있습니다 . 또는 life사용자 개체에 참조를 저장할 수 있습니다 . parent사용자는 객체에 대한 참조 일 뿐이고 다른 참조가있을 수 있기 때문에 언어로 사용할 수있는 고정이있을 수 없습니다 .

var death = { residents : life.users };
life.users.smallFurryCreaturesFromAlphaCentauri = { exist : function() {} };
// death.residents.smallFurryCreaturesFromAlphaCentauri now exists
//  - because life.users references the same object as death.residents!

다음과 같은 것을 사용하는 것이 도움이 될 수 있습니다.

function addChild(ob, childName, childOb)
{
   ob[childName] = childOb;
   childOb.parent = ob;
}

var life= {
        mameAndDestroy : function(group){ },
        kiss : function(group){ }
};

addChild(life, 'users', {
   guys : function(){ this.parent.mameAndDestroy(this.girls); },
   girls : function(){ this.parent.kiss(this.boys); },
   });

// life.users.parent now exists and points to life

내가 귀하의 질문을 올바르게 읽고 있다면 일반적으로 객체는 어디에 포함되어 있는지 알 수 없습니다. 그들은 그들의 부모가 누구인지 모릅니다. 해당 정보를 찾으려면 상위 데이터 구조를 구문 분석해야합니다. DOM에는 문서의 요소 객체에 대해 이야기 할 때이를 수행하는 방법이 있지만 바닐라 객체에 대해 이야기하는 것처럼 보입니다.


통화 정보 :

다음을 사용하여이 문제를 해결할 수 있습니다 .call().

  • 함수에서 호출되어야합니다. addName.call()
  • "this"가 되고자하는 객체를 전달합니다. addName.call({"name" : 'angela'});
  • boolean 인수를 허용하는 addName.call({"name": "angela"}, true);위치에서 호출되는 함수에서 사용할 수있는 추가 인수를 전달할 수 있습니다 .addNameappend

전화 사용 :

이 특정 문제의 경우 "부모"개체를 통해 자식 개체에 일반적으로 존재 call하는 것을 재정의 할 수 있습니다 this.

먼저 우리 문제를 봐

var app = {
    init: function() {
        var _this = this; // so we can access the app object in other functions

        $('#thingy').click(function(){
            alert(_this.options.thingy());
        });

        $('#another').click(function(){
            alert(_this.options.getAnother());
        });
    },
    options: {
      thingy: function() {
      // PROBLEM: the this here refers to options
        return this.getThingy();
      },
      getAnother: function() {
        // PROBLEM 2: we want the this here to refer to options,
        // but thingy will need the parent object
        return 'another ' + this.thingy();
      },
    },
    getThingy: function() {
        return 'thingy';
    }
};

자, 여기 솔루션 사용 호출이 있습니다.

그리고 JSFIDDLE 이 작동하는지 확인하십시오.

var app = {
    init: function() {
        var _this = this; // so we can access the app object in other functions

        $('#thingy').click(function(){
            // SOLUTION: use call to pass _this as the 'this' used by thingy
            alert(_this.options.thingy.call(_this));
        });

        $('#another').click(function(){
            // SOLUTION 2: Use call to pass parent all the way through
            alert(_this.options.getAnother.call(_this)); 
        });
    },
    options: {
      thingy: function() {
        // SOLUTION in action, the this is the app object, not options.
        return this.getThingy(); 
      },
      getAnother: function() {
        // SOLUTION 2 in action, we can still access the options 
        // AND pass through the app object to the thingy method.
        return 'another ' + this.options.thingy.call(this); 
      },
    },
    getThingy: function() {
        return 'thingy';
    }
};

결론적으로

.call()주 개체의 속성에 대한 메서드를 사용할 때마다 사용할 수 있습니다 . app.options.someFunction(arg)항상 .call- 로 호출해야 합니다. 이렇게 하면 항상 개체의 app.options.someFunction.call(this, arg);모든 부분에 액세스 할 수 있습니다. 같은 다른 속성의 메서드에 액세스 할 수 있습니다 app.helpers.anotherFunction().

좋은 아이디어는 , 변수에 somefunction저장 this하는 _parentThis것이므로이 무엇을 this반영 하는지 분명 합니다.


여기 있습니다 :

var life={
        users:{
             guys:function(){ life.mameAndDestroy(life.users.girls); },
             girls:function(){ life.kiss(life.users.guys); }
        },
        mameAndDestroy : function(group){ 
          alert("mameAndDestroy");
          group();
        },
        kiss : function(group){
          alert("kiss");
          //could call group() here, but would result in infinite loop
        }
};

life.users.guys();
life.users.girls();

또한 "girls"정의 뒤에 쉼표가 없는지 확인하십시오. 이로 인해 IE에서 스크립트가 충돌 할 수 있습니다 (IE에서 배열의 마지막 항목 뒤에 쉼표가있을 때마다 죽습니다).

실행 확인


다른 사람들이 말했듯이 중첩 된 자식에서 부모를 직접 조회하는 것은 불가능합니다. 제안 된 모든 솔루션은 명시 적 변수 이름을 통해 부모 개체 또는 부모 범위를 다시 참조하는 다양한 방법을 권장합니다.

그러나 부모 개체에 재귀 ES6 프록시 를 사용하면 부모 개체까지 직접 순회 할 수 있습니다 .

저는 ObservableSlim 이라는 라이브러리를 작성했습니다.이 라이브러리를 사용하면 자식 개체에서 부모로 이동할 수 있습니다.

다음은 간단한 예입니다 ( jsFiddle 데모 ) :

var test = {"hello":{"foo":{"bar":"world"}}};
var proxy = ObservableSlim.create(test, true, function() { return false });

function traverseUp(childObj) {
    console.log(JSON.stringify(childObj.__getParent())); // returns test.hello: {"foo":{"bar":"world"}}
    console.log(childObj.__getParent(2)); // attempts to traverse up two levels, returns undefined because test.hello does not have a parent object
};

traverseUp(proxy.hello.foo);

싱글 톤 패턴과 유사한 것을 사용했습니다.

function myclass() = {
    var instance = this;

    this.Days = function() {
        var days = ["Piątek", "Sobota", "Niedziela"];
        return days;
    }

    this.EventTime = function(day, hours, minutes) {
        this.Day = instance.Days()[day];
        this.Hours = hours;
        this.minutes = minutes;
        this.TotalMinutes = day*24*60 + 60*hours + minutes;
    }
}

나는 이와 같은 것을 해왔고 그것은 매력처럼 작동합니다.

단순한.

추신 더 많은 물건이 있지만 방금 관련 부분을 게시했습니다.

var exScript = (function (undefined) {
    function exScript() {
        this.logInfo = [];
        var that = this;
        this.logInfo.push = function(e) {
            that.logInfo[that.logInfo.length] = e;
            console.log(e);
        };
    }
})();

다음 코드를 사용하여 객체의 부모에 액세스 할 수 있습니다.

var Users = function(parent) {
    this.parent = parent;
};
Users.prototype.guys = function(){ 
    this.parent.nameAndDestroy(['test-name-and-destroy']);
};
Users.prototype.girls = function(){ 
    this.parent.kiss(['test-kiss']);
};

var list = {
    users : function() {
        return new Users(this);
    },
    nameAndDestroy : function(group){ console.log(group); },
    kiss : function(group){ console.log(group); }
};

list.users().guys(); // should output ["test-name-and-destroy"]
list.users().girls(); // should output ["test-kiss"]

Objects 로 작업 할 수있는 방법을 알기 위해 javascript Objects대해 읽어 보는 것이 좋습니다 . 많은 도움이되었습니다. 심지어 존재한다는 사실조차 몰랐던 기능에 대해서도 알아 냈습니다.


리터럴 객체 ( {}) 에서 노드의 모든 부모 키를 얻으려면 다음 과 같이 할 수 있습니다.

(function ($) {
    "use strict";

    $.defineProperties($, {
        parentKeys: {
            value: function (object) {
                var
                    traces = [],
                    queue = [{trace: [], node: object}],

                    block = function () {
                        var
                            node,
                            nodeKeys,
                            trace;

                        // clean the queue
                        queue = [];
                        return function (map) {
                            node = map.node;
                            nodeKeys = Object.keys(node);

                            nodeKeys.forEach(function (nodeKey) {
                                if (typeof node[nodeKey] == "object") {
                                    trace = map.trace.concat(nodeKey);
                                    // put on queue
                                    queue.push({trace: trace, node: node[nodeKey]});

                                    // traces.unshift(trace);
                                    traces.push(trace);
                                }
                            });
                        };
                    };

                while(true) {
                    if (queue.length) {
                        queue.forEach(block());
                    } else {
                        break;
                    }
                }

                return traces;
            },

            writable: true
        }

    });

})(Object);

이 알고리즘은 방법 FIFO을 사용하여 그래프를 반복 하는 개념을 사용합니다 BFS. 이 코드 는 매개 변수로 Javacript (해시 테이블-연관 배열 ...) 을 예상하는 Object정적 메소드 parentKeys추가 하는 클래스를 확장합니다 literal Object.

I hope I have helped.

ReferenceURL : https://stackoverflow.com/questions/183702/access-parents-parent-from-javascript-object

반응형