Advanced Object in js
The this Keyword in obj
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(dietType);
}
};
goat.diet();
// Output will be "ReferenceError: dietType is not defined"
Why? なぜgoat対象者は食事の仕方を記録する際にdietTypeに近づくことができないのか-That’s because inside the scope of the .diet() method, we don’t automatically have access to other properties of the goat object. オブジェクト内のメソッドは、同じオブジェクトのProperty DietTypeを転送することはできませんが、this.使用可能const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(this.dietType);
}
};
goat.diet(); // herbivore
オブジェクト内のこのキーワードを使用すると、オブジェクトのpropertyにアクセスできます.The this keyword references the calling object which provides access to the calling object’s properties. In the example above, the calling object is goat and by using this we’re accessing the goat object itself, and then the dietType property of goat by using property dot notation.
Arrow Functions and this keyword
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet: () => {
console.log(this.dietType);
}
};
goat.diet(); // Prints undefined
출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
Arrow functions inherently bind, or tie, an already defined this value to the function itself that is NOT the calling object. In the code snippet above, the value of this is the global object, or an object that exists in the global scope, which doesn’t have a dietType property and therefore returns undefined.Alow関数では、thisは常に親環境を囲むthisが継承するLexicalthisに従います.
const Foo = () => { console.log(this); }
const foo = new Foo(); // TypeError: Foo is not a constructor
출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
const person = { name: 'Lee', };
Object.prototype.sayHi = () => console.log(`Hi ${this.name}`);
person.sayHi(); // Hi undefined
//출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
const box = document.getElementById('box');
box.addEventListener('click', () => { console.log(this); //window });
출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
画像ソース:Dmtri Pavlutin
Privacy for object in js
When discussing privacy in objects, we define it as the idea that only certain properties should be mutable or able to change in value.
Certain languages have privacy built-in for objects, but JavaScript does not have this feature. Rather, JavaScript developers follow naming conventions that signal to other developers how to interact with a property. One common convention is to place an underscore _ before the name of a property to mean that the property should not be altered.
const person = {
_firstName: 'John',
_lastName: 'Doe',
get fullName() {
if (this._firstName && this._lastName){
return `${this._firstName} ${this._lastName}`;
} else {
return 'Missing a first name or a last name.';
}
}
}
// To call the getter method:
person.fullName; // 'John Doe'
Setters for object in js
Along with getter methods, we can also create setter methods which reassign values of existing properties within an object.
const person = {
_age: 37,
set age(newAge){
if (typeof newAge === 'number'){
this._age = newAge;
} else {
console.log('You must assign a number to age');
}
}
};
Nonetheless, even with a setter method, it is still possible to directly reassign properties. For example, in the example above, we can still set ._age directly:person._age = 'forty-five'
console.log(person._age); // Prints forty-five
ファクトリ機能ファクトリ関数
There are times where we want to create many instances of an object quickly. Here’s where factory functions come in.
A factory function is a function that returns an object and can be reused to make multiple object instances.
const monsterFactory = (name, age, energySource, catchPhrase) => {
return {
name: name,
age: age,
energySource: energySource,
scare() {
console.log(catchPhrase);
}
}
};
const ghost = monsterFactory('Ghouly', 251, 'ectoplasm', 'BOO!');
ghost.scare(); // 'BOO!'
GetterとSetterはなぜ書きますか?
もちろん、2つのgetter、setterオブジェクトプロパティアクセスメソッドを使用しても、他の開発者は直接オブジェクト値を割り当てたり変更したりすることができます.しかし、これによりプロジェクトで避けられない予期せぬ事故(予期せぬ結果やエラー)が発生する可能性があるため、getterとsetterを使用して他の開発者にコードの意図を通知することができます.(つまり、このオブジェクトはgetterとsetterを使用するので、勝手に値を変更することなく、色を与えることができます)
const dailyMenuSystem = {
dish: '햄버거',
price: 0,
}
Property Value Shorthand
ES6 introduced some new shortcuts for assigning properties to variables known as destructuring.
In the previous exercise, we created a factory function that helped us create objects. We had to assign each property a key and value even though the key name was the same as the parameter name we assigned to it.
const monsterFactory = (name, age) => {
return {
name,
age
}
};
Destructured Assignment
const vampire = {
name: 'Dracula',
residence: 'Transylvania',
preferences: {
day: 'stay inside',
night: 'satisfy appetite'
}
};
// Too much keystrokes
const residence = vampire.residence;
console.log(residence); // Prints 'Transylvania'
// basic destructured assignment
const { residence } = vampire;
console.log(residence); // Prints 'Transylvania'
// Renaming variables when destructring obj
const {residence: address} = vampire;
Review 2
getters/setters === access property by javascript.info
工場/建設者/クラスby fromnowwon
Factory functions vs Constructors by https://chamikakasun.medium.com/javascript-factory-functions-vs-constructor-functions-585919818afe
Destructuring assignment
Reference
この問題について(Advanced Object in js), 我々は、より多くの情報をここで見つけました https://velog.io/@shinyo627/Advanced-Object-in-jsテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol