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に従います.
  • Arow関数はオブジェクトメソッドとして使用できません.これはグローバルオブジェクトを指します.
  • Arow関数は構造関数として使用できません.コンストラクション関数でコンストラクション関数を作成することはできません.arrow関数にはプロトタイプがないからです.
  • const Foo = () => { console.log(this); } 
    
    const foo = new Foo(); // TypeError: Foo is not a constructor
    
    출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
  • メソッドをプロトタイプに割り当てると、Arow関数を使用すると問題が発生します.
  • const person = { name: 'Lee', }; 
    
    Object.prototype.sayHi = () => console.log(`Hi ${this.name}`); 
    
    person.sayHi(); // Hi undefined
    
    //출처: https://kim-solshar.tistory.com/57 [김솔샤르의 인사이트]
  • addEventListenerのコールバック関数は矢印関数ではありません.wx-brow関数は親範囲のこの点を継承するため、この場合、ウィンドウを指します.一般関数に変更します.
  • 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'
  • Getters can perform an action on the data when getting a property.
  • Getters can return different values using conditionals.
  • In a getter, we can access the properties of the calling object using this.
  • The functionality of our code is easier for other developers to understand.
  • Another thing to keep in mind when using getter (and setter) methods is that properties cannot share the same name as the getter/setter function. If we do so, then calling the method will result in an infinite call stack error. One workaround is to add an underscore before the property name like we did in the example above.

    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

  • The object that a method belongs to is called the calling object.
  • The this keyword refers to the calling object and can be used to access properties of the calling object.
  • Methods do not automatically have access to other internal properties of the calling object.
  • The value of this depends on where the this is being accessed from.
  • We cannot use arrow functions as methods if we want to access other internal properties.
  • JavaScript objects do not have built-in privacy, rather there are conventions to follow to notify other developers about the intent of the code.
  • The usage of an underscore before a property name means that the original developer did not intend for that property to be directly changed.
  • Setters and getter methods allow for more detailed ways of accessing and assigning properties.
  • Factory functions allow us to create object instances quickly and repeatedly.
  • There are different ways to use object destructuring: one way is the property value shorthand and another is destructured assignment.
  • Useful Refs:
    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