简体   繁体   中英

What is the different between these

I have been using java script , jquery sometime. but I still couldn't figure out proper definitions of below declaration of java script

var person = function(){
  name  = "Person1";
  age ="24"
}

function Person (){
  name  = "Perlson1";
  age ="24";     
}

var Person = {
  name : "Person1",
  age : "24",
}

Could anyone give me proper explanation to these three type,I am bit confused the way implementing within my project,

I would really appreciate it

They are not the same.

In the first two examples, you defined a function, and what the function do is set the values of two global variables name and age .

The third example is to define a normal object, which has properties with name and age .

The first two most likely should be below:

function Person(name, age){
  this.name = name;
  this.age = age;     
}

var person1 = new Person('Person1', 24);

The first is the same as the second, creating a function named Person .

The third however, creates an object called Person which has the properties name and age set.

So using the third,

alert(Person.name); // alerts `Person1`
alert(Person.age); // alerts `24`
var person = function(){
  name  = "Person1";
  age ="24"
}

The above code defines a variable 'person', which is assigned an anonymous function that sets the values for 2 global variables 'name' and 'age'.

function Person (){
  name  = "Perlson1";
  age ="24";     
}

The above code defines a function that sets the values for 2 global variables 'name' and 'age'. So, syntactically 1st & 2nd are different way of defining the function. But, they serve the same purpose. To access them, console.log(name); //or console.log(window.name); console.log(age); //or console.log(window.age);


var Person = {
  name : "Person1",
  age : "24",
}

The above 3rd code block is just an Object. It cannot be called by any other code. This just defines the object Person, which has 2 properties 'name' and 'age'. Note that here, the 2 properties - name and age belong to the Person object and not to the window. ie they are not global variables. They are bound to Person object. To access these, console.log(Person.name); console.log(Person.age);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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