明确地说,this.foo手段(如你了解也行)。你有兴趣有关财产foo通过引用当前对象的this。因此,如果您使用:this.foo = 'bar';您将设置foo由thisequals引用的当前对象的属性bar。
thisJavaScript 中的关键字并不总是与 C++ 中的相同。这里我可以给你举个例子:
function Person(name) {
   this.name = name;
   console.log(this); //Developer {language: "js", name: "foo"} if called by Developer
}
function Developer(name, language) {
   this.language = language;
   Person.call(this, name);
}
var dev = new Developer('foo', 'js');
在上面的示例中,我们使用函数Person的上下文调用函数,Developer因此this引用了将由Developer. 正如您从console.log结果中看到的那样,this来自Developer. 使用方法的第一个参数,call我们指定调用函数的上下文。
如果您不使用this简单的属性,您创建的属性将是一个局部变量。您可能知道 JavaScript 具有函数作用域,因此变量将是局部的,仅对声明它的函数可见(当然,它是在父函数内部声明的所有子函数)。下面是一个例子:
function foo() {
    var bar = 'foobar';
    this.getBar = function () {
        return bar;
    }
}
var f = new foo();
console.log(f.getBar());  //'foobar'
使用var关键字时确实如此。这意味着您将定义bar为局部变量,如果您忘记了var不幸bar将成为全局变量。
function foo() {
    bar = 'foobar';
    this.getBar = function () {
        return bar;
    }
}
var f = new foo();
console.log(window.bar);  //'foobar'
正是本地范围可以帮助您实现隐私和封装,这是 OOP 的最大好处之一。
现实世界的例子:
function ShoppingCart() {
    var items = [];
    this.getPrice = function () {
       var total = 0;
       for (var i = 0; i < items.length; i += 1) {
          total += items[i].price;
       }
       return total;
    }
    this.addItem = function (item) {
        items.push(item);
    }
    this.checkOut = function () {
        var serializedItems = JSON.strigify(items);
        //send request to the server...
    }
}
var cart = new ShoppingCart();
cart.addItem({ price: 10, type: 'T-shirt' });
cart.addItem({ price: 20, type: 'Pants' });
console.log(cart.getPrice()); //30
JavaScript 作用域优势的另一个例子是Module Pattern。在module模式中,您可以使用 JavaScript 的本地功能范围来模拟隐私。通过这种方法,您可以同时拥有私有属性和方法。下面是一个例子:
var module = (function {
    var privateProperty = 42;
    function privateMethod() {
        console.log('I\'m private');
    }
    return {
       publicMethod: function () {
           console.log('I\'m public!');
           console.log('I\'ll call a private method!');
           privateMethod();
       },
       publicProperty: 1.68,
       getPrivateProperty: function () {
           return privateProperty;
       },
       usePublicProperty: function () {
           console.log('I\'ll get a public property...' + this.publicProperty);
       }
    }
}());
module.privateMethod(); //TypeError
module.publicProperty(); //1.68
module.usePublicProperty(); //I'll get a public property...1.68
module.getPrivateProperty(); //42
module.publicMethod(); 
/*
 * I'm public!
 * I'll call a private method!
 * I'm private
 */
无父函数包装匿名函数有一些奇怪的语法,但暂时忘记它(它只是在初始化后执行函数)。功能可以从使用示例中看出,但好处主要在于提供一个简单的公共接口,该接口不会让您参与所有实现细节。有关该模式的更详细说明,您可以查看我上面放置的链接。
我希望通过this:-) 信息帮助您了解 JavaScript 的一些基本主题。