What is the difference between these two code samples?

后端 未结 3 529
梦谈多话
梦谈多话 2020-12-29 13:41

Code 1:

var Something = {
name: \"Name\",
  sayHi: function(){
     alert(Something.name);
  }
}

Code 2:

 function Somethin         


        
3条回答
  •  醉梦人生
    2020-12-29 14:02

    In the first code snippet, Something is a simple object, and not a constructor. In particular, you cannot call:

    var o = new Something();
    

    Such a form of creating objects is perfect for singletons; objects of which you only need one instance.

    In the second snippet, Something is a constructor, and you can use the new keyword with it.

    Edit:

    Also, in your second snippet, since you are using Something.name as opposed to this.name, it will always alert the name of the constructor itself, which is "Something", unless you override that property with something like Something.name = "Cool";.

    You probably wanted that line to say:

    alert(this.name);
    

提交回复
热议问题