![](/img/trans.png)
[英]What is the difference between declaring javascript objects with var vs. with function?
[英]Declaring variables in JavaScript class: this vs. var. Difference?
在声明JavaScript类中的内部变量与此 vs var之间有什么区别?
例:
function Foo( ) {
var tool = 'hammer';
}
function Foo2( ) {
this.tool = 'hammer';
}
我们所知道的一个区别是Foo2.tool会产生“锤子”,而Foo.tool会产生未定义的。
还有其他差异吗? 一对一的建议?
谢谢!
这里没有“一个或另一个”,因为两者的目的不同。
考虑一下:
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
实例,我可以访问和修改weapon
因为它向公众开放。
handitem.tool
是一个“私有财产”。 它只能从对象内部访问。 它不可见,不可访问,并且不能从外部修改(至少直接)。 试图访问它将返回undefined
handitem.getTool
是一个“公共方法”。 因为它位于对象的内部,所以它可以访问私有属性tool
并从外部获取它。 通往私人世界的桥梁。
handitem.attack
是一种私有方法。 像所有私人东西一样,它只能从内部访问。 在这个例子中,没有办法调用attack()
(所以我们可以免受攻击:D)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.