简体   繁体   中英

Differences between javascript constructor functions

What is the difference between this...

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

and this...

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

and this...

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

Thanks!


David, I have a piece of code for a game I am building that looks like this...

function Player(node){
    this.node = node;
    this.grace = false;
    this.replay = 3; 
    this.shield = 3;
    this.respawnTime = -1;
  ...
return true;
}

and it does not return a reference error. Its an object for a player in a javascript game I am building...

第一种依赖于通过参数设置的局部变量来设置其实例变量/属性,第三种依赖于全局变量来设置其属性,第二种是混合。

As Brett said, the second and third constructor function will assign any global variable to the properties of the new Person instance. However, you can still use any argument that might be passed to the constructor:

function Person()//no args
{
    //depending on which value is available:
    //prop = n-th argument OR global variable OR undefined
    this.name = arguments[0] || window.name || undefined;
    this.age = arguments[1] || window.age || undefined;
    this.sex = arguments[2] || window.sex || undefined;
}
var parrot = new Person('polly',1,'M');
console.log(parrot.name);//polly
var noSex = new Person('Joe',99);//if no global sex is set:
console.log(noSex.sex);//undefined
var sex = 'F';
var jane = new Person('Jane',25);
console.log(jane.sex);//F

1st one is valid, you initite your local variables with the parameters sent in the constructor. the rest doesnt really make sense.

in the 2nd one you kind of mixing parameters with some other variables which you can access at that point, you initate only the name using a parameter.

and the 3rd one is based on accessable variables, but none of them is given as a parameter, i never saw something usefull using 2nd and 3rd options..

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