在 JavaScript 类中,使用 this 和 var 声明内部变量有什么区别呢?
例如:
function Foo( ) {
var tool = 'hammer';
}
function Foo2( ) {
this.tool = 'hammer';
}
我们已经知道的一个区别是,Foo2.tool会返回“hammer”,而Foo.tool会返回undefined。
还有其他区别吗?您对其中一个与另一个有何建议?
谢谢!
在 JavaScript 类中,使用 this 和 var 声明内部变量有什么区别呢?
例如:
function Foo( ) {
var tool = 'hammer';
}
function Foo2( ) {
this.tool = 'hammer';
}
这里不存在“二选一”,因为这两个的目的是不同的。
考虑以下情况:
var Melee = function(){
//private property
var tool = 'hammer';
//private method
var attack = function(){
alert('attack!');
};
//public property
this.weapon = 'sword';
//public methods
this.getTool = function(){
return tool; //can get private property tool
};
this.setTool = function(name){
tool = name; //can set private property tool
};
};
var handitem = new Melee();
var decoration = new Melee();
//public
handitem.weapon; //sword
handitem.getTool(); //hammer
handitem.setTool('screwdriver'); //set tool to screwdriver
handitem.getTool(); //is now screwdriver
//private. will yield undefined
handitem.tool;
handitem.attack();
//decoration is totally different from handitem
decoration.getTool(); //hammer
handitem.weapon
在面向对象编程中是一个“公共属性”,可以从外部访问。如果我创建了这个Melee
实例,我可以访问和修改weapon
,因为它对外开放。
handitem.tool
是一个“私有属性”。只能从对象内部访问它。它不可见、不可访问,也不能(至少直接)从外部修改。尝试访问它将返回undefined
handitem.getTool
是一个“公共方法”。由于它在对象内部,它可以访问私有属性tool
并从外部获取它。是连接私有世界的桥梁。
handitem.attack
是一个私有方法。像所有私有内容一样,它只能从内部访问。在这个例子中,无法调用attack()
(所以我们安全免受攻击:D)
new Melee()
都会创建一个新对象。更新一个对象的属性不会改变另一个对象的值。 - Josephnew
关键字时,将会创建一个新的独特对象并传递给 Melee
函数。因此每个对象都有自己独立的 weapon
属性。然而,在 @Joseph 的代码中,tool
变量是函数作用域变量,所以你不能直接从函数外部修改它。你需要一个 setTool
方法来实现修改。 - Peter LyonsbuyTool()
方法在哪里?它在对象中吗?它是私有的还是公共的? - Joseph
this.tool
的理由,就使用var tool
。 - Blendervar tool
,因此它不是为在类外部使用而设计的。this.tool
是为了从类外部调用而设计的。 - Blender