What is a best practice for ensuring “this” context in Javascript?

后端 未结 8 1424
刺人心
刺人心 2021-02-14 20:37

Here\'s a sample of a simple Javascript class with a public and private method (fiddle: http://jsfiddle.net/gY4mh/).

function Example() {
    function privateFun         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-14 21:06

    Another approach is to use "apply" to explicitly set what the methods "this" should be bound to.

    function Test() {
        this.name = 'test';
        this.logName = function() {
            console.log(this.name);
        }
    }
    
    var foo = {name: 'foo'};
    
    var test = new Test();
    test.logName()
    // => test
    test.logName.apply(foo, null);
    // => foo
    

    Yet another approach is to use "call":

    function Test() {
        this.name = 'test';
        this.logName = function() {
            console.log(this.name);
        }
    }
    
    var foo = {name: 'foo'};
    
    var test = new Test();
    test.logName()
    // => test
    test.logName.call(foo, null);
    // => foo
    

    both "apply" and "call" take the object that you want to bind "this" to as the first argument and an array of arguments to pass in to the method you are calling as the second arg.

提交回复
热议问题