オブジェクト向けプログラミング

18187 ワード

方法


メソッドは、関数値を持つプロパティです.
harry = {
  name: 'Harry',
  salary : 800,
  raiseSalary: function (percent) {
    this.salary *= 1 + percent / 100
  }
}
// 편의문법 syntactic sugar 
harry = {
  name: 'Harry',
  salary : 800,
  raiseSalary (percent) {
    this.salary *= 1 + percent / 100
  }
}

プロトタイプ


複数のオブジェクトに共通に含まれるプロパティのセットをPrototypeとします.
const employeePrototype = {
  raiseSalary : function(percent) {
    this.salary *= 1 + percent / 100
  }
}

function createEmployee(name, salary) {
  const result = {name, salary}
  Object.setPrototypeOf(result, employeePrototype)
  return result
}
// obj.__proto__ 로 프로토타입에 접근가능하지만 표준문법이 아니므로 사용하지 말자

生成者

function Employee(name, salary) {
  this.name = name
  this.salary = salary
}

Employee.prototype.raiseSalary = function(percent) {
  this.salary *= 1 + percent / 100
}
下と全く同じです.次は文法です.
class Employee{
  constructor(name, salary) {
    this.name = name
    this.salary = salary
  }
  raiseSalary(percent) {
    this.salary *= 1 + percent / 100
  }
}
みんなは次のように呼んだ.
const harry = new Employee('harry', 8000)

参照

// 콜백함수에서 this 사용
class BankAccount {
  ...
  spreadTheWealth(accounts) {
    accounts.forEach(function(account) {
    	account.deposit(this.balance / accounts.length)
        // 중첩함수안에서 this 는 undefined이므로 오류발생
  	})
  	this.balance = 0
  }
}

// 화살표함수사용
class BankAccount {
  ...
  spreadTheWealth(accounts) {
    accounts.forEach((account) => {
    	account.deposit(this.balance / accounts.length)
        // 올바로 동작
  	})
  	this.balance = 0
  }
}

// 콜백함수에서 다른변수에 this 초기화
class BankAccount {
  ...
  const that = this
  spreadTheWealth(accounts) {
    accounts.forEach(function(account) {
    	account.deposit(that.balance / accounts.length)
        // this 대신 변수 that 사용
  	})
  	this.balance = 0
  }
}

練習問題

let createPoint = function (x, y) {
  x:x
  y:y
  translate: function(x1, y1) {
    this.x += x1
    this.y += y1
  }
  scale: function(xtimes, ytimes) {
    this.x *= xtimes
    this.y *= ytimes
  }
}
const pointPrototype =  {
  translate: function(x1, y1) {
    this.x += x1
    this.y += y1
  }
  scale: function(xtimes, ytimes) {
    this.x *= xtimes
    this.y *= ytimes
  }  
}
function createPoint(x, y) {
  const result = {x, y}
  Object.setPrototypeOf(result, pointPrototype)
  return result
}
class Point {
  constructor(x, y) {
    this.x = x
    this.y = y
  }
  translate(x1, y1) {
    this.x += x1
    this.y += y1
  }
  scale(xtimes, ytimes) {
    this.x *= xtimes
    this.y *= ytimes
  } 
}