简体   繁体   English

在JavaScript类中声明变量:this vs. var。 区别?

[英]Declaring variables in JavaScript class: this vs. var. Difference?

What's the difference between declaring internal variables inside a JavaScript class with this vs var ? 在声明JavaScript类中的内部变量与 vs var之间有什么区别?

Example: 例:

function Foo( ) {
   var tool = 'hammer';
}

function Foo2( ) {
   this.tool = 'hammer';
}

One difference we're aware of is Foo2.tool will yield "hammer" whereas Foo.tool will yield undefined. 我们所知道的一个区别是Foo2.tool会产生“锤子”,而Foo.tool会产生未定义的。

Are there other differences? 还有其他差异吗? Recommendations for one vs. the other? 一对一的建议?

Thanks! 谢谢!

there is no "one or the other" here since the purpose of the two are different. 这里没有“一个或另一个”,因为两者的目的不同。

consider this: 考虑一下:

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 in OOP is a "public property", accessible from the outside. OOP中的handitem.weapon是一个“公共财产”,可从外部访问。 if i created this instance of Melee , i can access and modify weapon since it's open to the public. 如果我创建了这个Melee实例,我可以访问和修改weapon因为它向公众开放。

  • handitem.tool is a "private property". handitem.tool是一个“私有财产”。 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 return undefined 试图访问它将返回undefined

  • handitem.getTool is a "public method". handitem.getTool是一个“公共方法”。 since it's on the inside of the object, it has access the private property tool and get it for you from the outside. 因为它位于对象的内部,所以它可以访问私有属性tool并从外部获取它。 sort of bridge to the private world. 通往私人世界的桥梁。

  • handitem.attack is a private method. handitem.attack是一种私有方法。 like all private stuff, it can only be accessed from the inside. 像所有私人东西一样,它只能从内部访问。 in this example, there is no way to call attack() (so we are safe from attack :D ) 在这个例子中,没有办法调用attack() (所以我们可以免受攻击:D)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM