繁体   English   中英

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

[英]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.

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