给定以下代码,我们可以看到闭包帮助将变量的值包含在其作用域内:

var f = new Foo('jim','jam');
var b = new Bar('saul','paul');
var bz = new Baz();

function Foo(jim,jam){

    this.jim = jim;
    this.jam = jam;

    function log(){
        console.log('jim:',jim,'jam:',jam);
    }

    return log;
}


function Bar(jim,jam){

    function log(){
        console.log('jim:',jim,'jam:',jam);
    }

    return log;
}

function Baz(jim,jam){

    this.jim = 'bark';
    this.jam = 'catch';


    function log(){
        console.log('jim:',this.jim,'jam:',this.jam);
    }

    return log;
}

f();
b();
bz();


那么,JavaScript中'this'关键字的用途到底是什么呢?什么时候有必要?

最佳答案

this关键字用于访问当前上下文,该上下文与当前作用域不同。

如果调用对象的方法,则该调用的上下文是对象。您可以使用this关键字来访问对象中的属性:



function Foo(jim,jam){
    this.x = jim;
    this.y = jam;
}

Foo.prototype.log = function(){
    document.write('jim:' + this.x + ', jam:' + this.y);
};

var f = new Foo('jim','jam');
f.log();

10-04 14:04