본문 바로가기

기존카테고리/javascript & jQuery

call()

https://www.w3schools.com/js/js_function_call.asp


Ex1:

var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
}
person.fullName();         // Will return "John Doe"



Ex2:

var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
person.fullName.call(myObject);  // Will return "Mary Doe"





call() 은 타 객체를 부른다.

타 객체 호출 시 기존 객체는 사라짐.



var hi = {

    firstName : "John",

    lastName : "Doe",

    morning : function() {

        console.log('하이 '+this.userName+'님');

        console.log('하이 '+this.userJob+'님');

        console.log('하이 '+this.firstName+'님');

        console.log('하이 '+this.lastName+'님');

    }

    // console.log('이름 '+this.firstName+'님');

}


var userGroup = {

    userName: '강호동',

    userJob: '예능인'

}


hi.morning.call(userGroup);


결과:

하이 강호동님

하이 예능인님

하이 undefined님

하이 undefined님



'기존카테고리 > javascript & jQuery' 카테고리의 다른 글

ajax 사용법  (0) 2018.02.03
jQuery 별칭 설정  (0) 2017.12.06
정리요약  (0) 2017.10.28