JavaScript, доступ к свойству возможен только с подчеркиванием _ - PullRequest
0 голосов
/ 28 февраля 2019

Я работал над кодом для создания вложенного / рекурсивного дерева объектов / массивов.После добавления получателей / установщиков к объекту я могу получить доступ только к свойствам в корне дерева, используя префикс «_».Смотрите строку 89 кода, почти внизу, где начинаются файлы console.logs.

// My intention is to create a single “template” object definition that can be used to build a tree of sline / leaves of the same object.
// Also functions are created that can get/set values of any properties for any leaf using an array representing the position of the leaf in the tree.

// Create Sline/Leaf Object Template
class objTemplate {
    constructor(SpineName, Width, Height) {
        this.SpineName = SpineName;
        this.Width = Width;
        this.Height = Height;
        this.Area;
        this.Leaves = [];
    }

    get SpineName() {
        return this._SpineName;
    }

    set SpineName(value) {
        if (value.length === 0) {
            console.log("Sline Name Is Required.");
            return;
        }
        this._SpineName = value;
    }

    get Width() {
        return this._Width;
    }

    set Width(value) {
        this._Width = value;
        this._Area = this._Width * this._Height;
    }

    get Height() {
        return this._Height;
    }

    set Height(value) {
        this._Height = value;
        this._Area = this._Width * this._Height;
    }

    get Area() {
        return this._Area;
    }

}

// Push Leaf bject To Tree 
function pushLeaf(Position, Tree, NewLeaf) {
    Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree).Leaves.push(NewLeaf);
}

// Get Value From Leaf Object 
function getValue(Position, Tree, Key) {
    return Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree)[Key];
}

// Set Leaf Object Value 
function setValue(Position, Tree, Key, value) {
    Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree)[Key] = value;
}

// Create Initial Tree
var objTree = Object.assign(Object.create(Object.getPrototypeOf(objTemplate)), new objTemplate("Root", 4, 5));

// Add Under Root Object
pushLeaf([], objTree, new objTemplate("Oreo", 3, 4));
pushLeaf([], objTree, new objTemplate("Jupiter", 7, 3));

// Add Under Root / 1st Object 
pushLeaf([0], objTree, new objTemplate("Moonman", 5, 2));
pushLeaf([0], objTree, new objTemplate("Slade", 4, 4));
pushLeaf([0], objTree, new objTemplate("Bubba", 4, 6));

// Add Under Root / 2nd Object
pushLeaf([0], objTree, new objTemplate("Chicken Butt", 9, 5));
pushLeaf([0], objTree, new objTemplate("Boss", 3, 5));

// Add Under Root / 1st Object / 3rd Object
pushLeaf([[0], [2]], objTree, new objTemplate("Buddy", 6, 4));
pushLeaf([[0], [2]], objTree, new objTemplate("Roe", 4, 8));

// Add Under Root / 1st Object / 3rd Object / 2nd Object
pushLeaf([[0], [2], [1]], objTree, new objTemplate("Little Man", 6, 4));


console.log(`Root Object Spine Name: ${getValue([], objTree, "_SpineName")}`); // Where getters/setter are used, on root "_" prefx must be used for the property name
console.log(`Root Object / 1st Object Spine Name: ${getValue([0], objTree, "SpineName")}`);
console.log(`Root Object / 2nd Object Spine Name: ${getValue([1], objTree, "SpineName")}`);
console.log(`Root Object / 1st Object / 3rd object Spine Name: ${getValue([[0], [2]], objTree, "SpineName")}`);
console.log("");

console.log(`Root Object / 1st Object / 3rd object / 2nd Object Width: ${getValue([[0], [2], [1]], objTree, "Width")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Height: ${getValue([[0], [2], [1]], objTree, "Height")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Area: ${getValue([[0], [2], [1]], objTree, "Area")}`);
console.log("");

console.log('Change Root Object / 1st Object / 3rd object / 2nd Object Width:');
setValue([[0], [2], [1]], objTree, "Width", 8);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Width: ${getValue([[0], [2], [1]], objTree, "Width")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Height: ${getValue([[0], [2], [1]], objTree, "Height")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Area: ${getValue([[0], [2], [1]], objTree, "Area")}`);

//console.log(JSON.stringify(objTree));

Опять же, это проявилось только после добавления геттеров / сеттеров.Чтобы быть единообразным, я мог бы использовать префикс "_" при вызове всех свойств для объектов в других местах дерева.Но я не знаю, является ли это приемлемой практикой?Или что еще сделать по другому?Может быть, есть другой способ сделать то, чего я пытаюсь достичь?

1 Ответ

0 голосов
/ 28 февраля 2019

То, как вы создаете objTree с помощью Object.assign() и Object.create(), неправильно копирует прототип.

Если вы измените его на просто:

var objTree = new objTemplate("Root", 4, 5);

будет работать по желанию.Вот как вы создаете все вложенные объекты, я не вижу смысла создавать корень по-другому.

// My intention is to create a single “template” object definition that can be used to build a tree of sline / leaves of the same object.
// Also functions are created that can get/set values of any properties for any leaf using an array representing the position of the leaf in the tree.

// Create Sline/Leaf Object Template
class objTemplate {
    constructor(SpineName, Width, Height) {
        this.SpineName = SpineName;
        this.Width = Width;
        this.Height = Height;
        this.Area;
        this.Leaves = [];
    }

    get SpineName() {
        return this._SpineName;
    }

    set SpineName(value) {
        if (value.length === 0) {
            console.log("Sline Name Is Required.");
            return;
        }
        this._SpineName = value;
    }

    get Width() {
        return this._Width;
    }

    set Width(value) {
        this._Width = value;
        this._Area = this._Width * this._Height;
    }

    get Height() {
        return this._Height;
    }

    set Height(value) {
        this._Height = value;
        this._Area = this._Width * this._Height;
    }

    get Area() {
        return this._Area;
    }

}

// Push Leaf bject To Tree 
function pushLeaf(Position, Tree, NewLeaf) {
    Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree).Leaves.push(NewLeaf);
}

// Get Value From Leaf Object 
function getValue(Position, Tree, Key) {
    return Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree)[Key];
}

// Set Leaf Object Value 
function setValue(Position, Tree, Key, value) {
    Position.reduce((val, prop) => { return val.Leaves[prop]; }, Tree)[Key] = value;
}

// Create Initial Tree
var objTree = new objTemplate("Root", 4, 5);

// Add Under Root Object
pushLeaf([], objTree, new objTemplate("Oreo", 3, 4));
pushLeaf([], objTree, new objTemplate("Jupiter", 7, 3));

// Add Under Root / 1st Object 
pushLeaf([0], objTree, new objTemplate("Moonman", 5, 2));
pushLeaf([0], objTree, new objTemplate("Slade", 4, 4));
pushLeaf([0], objTree, new objTemplate("Bubba", 4, 6));

// Add Under Root / 2nd Object
pushLeaf([0], objTree, new objTemplate("Chicken Butt", 9, 5));
pushLeaf([0], objTree, new objTemplate("Boss", 3, 5));

// Add Under Root / 1st Object / 3rd Object
pushLeaf([[0], [2]], objTree, new objTemplate("Buddy", 6, 4));
pushLeaf([[0], [2]], objTree, new objTemplate("Roe", 4, 8));

// Add Under Root / 1st Object / 3rd Object / 2nd Object
pushLeaf([[0], [2], [1]], objTree, new objTemplate("Little Man", 6, 4));


console.log(`Root Object Spine Name: ${getValue([], objTree, "SpineName")}`); // Where getters/setter are used, on root "_" prefx must be used for the property name
console.log(`Root Object / 1st Object Spine Name: ${getValue([0], objTree, "SpineName")}`);
console.log(`Root Object / 2nd Object Spine Name: ${getValue([1], objTree, "SpineName")}`);
console.log(`Root Object / 1st Object / 3rd object Spine Name: ${getValue([[0], [2]], objTree, "SpineName")}`);
console.log("");

console.log(`Root Object / 1st Object / 3rd object / 2nd Object Width: ${getValue([[0], [2], [1]], objTree, "Width")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Height: ${getValue([[0], [2], [1]], objTree, "Height")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Area: ${getValue([[0], [2], [1]], objTree, "Area")}`);
console.log("");

console.log('Change Root Object / 1st Object / 3rd object / 2nd Object Width:');
setValue([[0], [2], [1]], objTree, "Width", 8);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Width: ${getValue([[0], [2], [1]], objTree, "Width")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Height: ${getValue([[0], [2], [1]], objTree, "Height")}`);
console.log(`Root Object / 1st Object / 3rd object / 2nd Object Area: ${getValue([[0], [2], [1]], objTree, "Area")}`);

//console.log(JSON.stringify(objTree));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...