在JavaScript类中声明变量:this vs. var.区别? [英] Declaring variables in JavaScript class: this vs. var. Difference?
问题描述
使用 this 与 var 在JavaScript类中声明内部变量之间有什么区别?
What's the difference between declaring internal variables inside a JavaScript class with this vs var?
示例:
function Foo( ) {
var tool = 'hammer';
}
function Foo2( ) {
this.tool = 'hammer';
}
我们知道的一个区别是Foo2.tool将产生锤子",而Foo.tool将产生未定义的东西.
One difference we're aware of is Foo2.tool will yield "hammer" whereas Foo.tool will yield undefined.
还有其他区别吗?对一个建议还是另一个建议?
Are there other differences? Recommendations for one vs. the other?
谢谢!
推荐答案
这里没有一个或另一个",因为两者的目的是不同的.
there is no "one or the other" here since the purpose of the two are different.
考虑这一点:
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
- OOP中的
-
handitem.weapon
是一个公共财产",可以从外部访问.如果我创建了这个Melee
实例,则可以访问和修改武器
,因为它是向公众开放的.handitem.weapon
in OOP is a "public property", accessible from the outside. if i created this instance ofMelee
, i can access and modifyweapon
since it's open to the public.handitem.tool
是私有财产".它只能从对象内部访问.它是不可见的,不可访问的,并且不能(至少直接)从外部进行修改.尝试访问它会返回undefined
handitem.tool
is a "private property". it's only accessible from inside the object. it is not visible, not accessible, and not modifiable (at least directly) from the outside. trying to access it will returnundefined
handitem.getTool
是一个公共方法".由于它位于对象的内部,因此可以访问私有属性tool
并从外部为您获取.通往私人世界的桥梁.handitem.getTool
is a "public method". since it's on the inside of the object, it has access the private propertytool
and get it for you from the outside. sort of bridge to the private world.handitem.attack
是一个私有方法.像所有私人物品一样,只能从内部进行访问.在此示例中,无法调用attack()
(因此我们可以免受攻击:D)handitem.attack
is a private method. like all private stuff, it can only be accessed from the inside. in this example, there is no way to callattack()
(so we are safe from attack :D )这篇关于在JavaScript类中声明变量:this vs. var.区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!