카테고리 없음

자바스크립트 bind 함수

Soul-Learner 2012. 6. 9. 20:29

functionname.bind(thisArg[,arg1[,arg2[,argN]]])

함수가 호출될 때 함수 안에서 this 키워드로 참조할 객체(thisArg)와 전달될 아규먼트 리스트

// Define the original function.
function showBind1() {
    var checkNumericRange = function (value) {
        if (typeof value !== 'number')
            return false;
        else
            return value >= this.minimum && value <= this.maximum;
    }

    // The objForThis argument enables use of the this value
    // within the callback function.
    var objForThis = { minimum: 10, maximum: 20 };

    // Create a new function that binds objForThis to
    // the checkNumericRange function.
    var chk = checkNumericRange.bind(objForThis);

    // Use the new function to check whether 12 is in the numeric range.
    var result = chk(12);
    document.write(result);
    // Output: true
}


다음은 함수 안에서 this키워드가 참조하는 객체가 원래의 객체가 아닌 다른 객체로 변경되는 예

function showBind2() {
    // Create an object that contains the original function.
    var objWithProps = {
        minimum: 50,
        maximum: 100,
        checkNumericRange: function (value) {
            if (typeof value !== 'number')
                return false;
            else
                return value >= this.minimum && value <= this.maximum;
        }
    }

    // Check whether 10 is in the numeric range.
    var result = objWithProps.checkNumericRange(10);
    document.write(result + " ");
    // Output: false

    var objForThis = { minimum: 10, maximum: 20 };

    // Create a new version of the checkNumericRange function.
    // For the new function, the object referred to by the
    // this keyword is different from the object that contains
    // the original function.
    var chk = objWithProps.checkNumericRange.bind(objForThis);

    // Using the new function, check whether 10 is in the numeric
    // range.
    var result = chk(10);
    document.write(result);
    // Output: true
}


bind 함수를 이용하여 특정 함수에 기본 아규먼트를 설정하는 예

function showBind3() {
    // Define the original function.
    var displayArgs = function (val1, val2, val3, val4) {
        document.write(val1 + " " + val2 + " " + val3 + " " + val4);
    }

    var objForThis = {};

    // Create a new function that is the same as the
    // original function, except that the 12 and "a" parameters
    // are always the first two parameters.
    var displayArgs2 = displayArgs.bind(objForThis, 12, "a");

    // Call the new function.
    displayArgs2("b", "c");
    // Output: 12 a b c 
}