明确地说,
this.foo
(正如您所理解的那样)意味着您对当前由
this
引用的对象的属性
foo
感兴趣。因此,如果您使用:
this.foo ='bar';
,则将使
this
所引用的当前对象的属性
foo
等于
bar
。
在JavaScript中,
this
关键字并不总是像C ++中那样意义相同。这里我可以给您一个例子:
function Person(name) {
this.name = name;
console.log(this);
}
function Developer(name, language) {
this.language = language;
Person.call(this, name);
}
var dev = new Developer('foo', 'js');
在上面的例子中,我们使用函数
Developer
作为上下文调用函数
Person
,因此
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());
当您使用var
关键字时,这是正确的。这意味着如果您忘记var
,则将bar
定义为局部变量,不幸的是bar
将变为全局。
function foo() {
bar = 'foobar';
this.getBar = function () {
return bar;
}
}
var f = new foo();
console.log(window.bar);
局部作用域可以帮助你实现面向对象编程(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);
}
}
var cart = new ShoppingCart();
cart.addItem({ price: 10, type: 'T-shirt' });
cart.addItem({ price: 20, type: 'Pants' });
console.log(cart.getPrice());
JavaScript作用域的又一个好处就是可以应用模块模式,在模块模式中,你可以通过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();
module.publicProperty();
module.usePublicProperty();
module.getPrivateProperty();
module.publicMethod();
有一个有点奇怪的语法,即将匿名函数包装在没有父级的函数中,但暂时忘记它(它只是在初始化后执行函数)。功能可以从使用示例中看到,但好处主要与提供简单的公共接口相关,而不涉及所有实现细节。有关该模式的更详细说明,请参见我上面提供的链接。
我希望通过这个信息,帮助您了解JavaScript的一些基本主题。
.bar
是一个对象属性,而不是变量。因此,如果要从对象中获取该属性,您需要通过对该对象的某些引用来实现。如果this
引用您的对象,则this.bar
将为您提供该属性。 - I Hate Lazythis.bar
和bar
不是完全相同的。不过你可以使用var bar = this.bar
,这样bar
就会引用this.bar
。 - Loktarthis.bar
是一个对象或数组时才这样做... - Alnitak