作用域安全的构造函数

一般构造函数定义和调用如下:

function Person(name,age,job)
{
   this.name=name;
   this.age=age;
   this.job=job; 
}
var person=new Person('thinksley',24,'web developer');
console.log(person.name); //thinksley

而如果实例化对象的时候不用new的话,this会映射到全局的window对象上,这时候person.name就会变成undefined了,要把对象改成window:

function Person(name,age,job)
{
   this.name=name;
   this.age=age;
   this.job=job; 
}
var person=Person('thinksley',24,'web developer');
console.log(window.name);//thinksley

console.log(person.name);//undefined

那么完整的构造函数可以用if判断来做了,如下

function Person(name,age,job)
{
  if(this instanceof Person)
  {
   this.name=name;
   this.age=age;
   this.job=job; 
  }
  else
  {
   return new Person(name,age,job); 
  }
}
var person=Person('thinksley',24,'web developer');
console.log(person.name);//thinksley

var person=new Person('thinksley',24,'web developer');
console.log(person.name); //thinskley

 这样构造函数就确保了this是否是Person对象的实例,要么使用new操作符,要么在现有的person实例环境中调用构造函数。

Top
收藏
关注
评论
原文地址:https://www.cnblogs.com/thinksley/p/2924098.html