함수 – 호출 방법

var add = function(a,b){
  return a+b;
}

// 호출패턴 4가지

//0. 메소드 호출 패턴 (객체내메소드 호출 패턴 (객체내 함수를 메소드라 함)
// *this 는 객체 자체가 된다.
var myObject = {
  value : 0,
  increment: function(inc){
    this.value += (typeof inc === 'number' ? inc : 1);
  }
};

myObject.increment(); // 인자가 number 타입이 아니니 value 에 1이 할당됨
console.log(myObject.value);

myObject.increment(2); // 인자가 number 이니까 기존 value 1+2 가 됨
console.log(myObject.value);


//1. 함수 호출 패턴
var sum = add(3,4);
// ㄴ이런거

myObject.double = function(){
//   var that = this;
  var helper = function(){
    this.value = add(this.value, this.value);
  };
  helper();
};

myObject.double();
console.log(myObject.value);



//2. 생성자 호출패턴

//지금 함수로만 보면 this 가 전역객체를 가르키지만 생성자로 사용할땐 유용하다.
var Quo = function(string){
  this.status = string;
}

// Quo 의 모든 인스턴스에 get_status 라는 public 메소드를 줌
Quo.prototype.get_status = function(){
  return this.status;
}
// ㄴQuo 에 프로퍼티를 추가하는게 아니라 Quo 의 prototype 에 속성을 추가하는 것임 

//Quo 인스턴스 생성
var myQuo = new Quo("confused");
console.log(myQuo.get_status());
// 일반적으로 생성자는 대문자로 시작해 구분하는 센스를 발휘해야된다.
// 크럭포드는 생성자 함수를 사용하는것은 권장사항이 아니라고 했다.

//3. apply 호출패턴
// apply 메소드는 함수를 호출할때 사용할 인수들의 배열을 받아들인다.
// this 의 값을 선택할 수 있도록 해준다!!!(첫번째인자)

// 배열을 이용하는 예제
var array = [3,4];
var sum = add.apply(null,array);

var statusObject = {
  status: "A-OK"
};
var status = Quo.prototype.get_status.apply(statusObject);
console.log(status);
//ㄴ 즉,Quo.prototype.get_status 메소드의 this 를 statusObject 로 바꿔줘서 그 status 를 리턴하는거다


 

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
모든 댓글 보기
0
생각을 나눠주시면 감사해요!x
()
x
Please enter Google Username or ID to start!
Example: clip360net or 116819034451508671546
Title
Caption
File name
Size
Alignment
Link to
  Open new windows
  Rel nofollow