![](/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.