您好,欢迎访问一九零五行业门户网

javascript中的作用域安全构造函数实例代码详解

作用域安全的构造函数
构造函数其实就是一个使用new操作符调用的函数
function person(name,age,job){ this.name=name; this.age=age; this.job=job; } var person=new person('match',28,'software engineer'); console.log(person.name);//match
如果没有使用new操作符,原本针对person对象的三个属性被添加到window对象
function person(name,age,job){ this.name=name; this.age=age; this.job=job; } var person=person('match',28,'software engineer'); console.log(person);//undefined console.log(window.name);//match
window的name属性是用来标识链接目标和框架的,这里对该属性的偶然覆盖可能会导致页面上的其它错误,这个问题的解决方法就是创建一个作用域安全的构造函数
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('match',28,'software engineer'); console.log(window.name); // "" console.log(person.name); //'match' var person= new person('match',28,'software engineer'); console.log(window.name); // "" console.log(person.name); //'match'
但是,对构造函数窃取模式的继承,会带来副作用。这是因为,下列代码中,this对象并非polygon对象实例,所以构造函数polygon()会创建并返回一个新的实例
function polygon(sides){ if(this instanceof polygon){ this.sides=sides; this.getarea=function(){ return 0; } }else{ return new polygon(sides); } } function rectangle(wifth,height){ polygon.call(this,2); this.width=this.width; this.height=height; this.getarea=function(){ return this.width * this.height; }; } var rect= new rectangle(5,10); console.log(rect.sides); //undefined
如果要使用作用域安全的构造函数窃取模式的话,需要结合原型链继承,重写rectangle的prototype属性,使它的实例也变成polygon的实例
function polygon(sides){ if(this instanceof polygon){ this.sides=sides; this.getarea=function(){ return 0; } }else{ return new polygon(sides); } } function rectangle(wifth,height){ polygon.call(this,2); this.width=this.width; this.height=height; this.getarea=function(){ return this.width * this.height; }; } rectangle.prototype= new polygon(); var rect= new rectangle(5,10); console.log(rect.sides); //2
以上就是javascript中的作用域安全构造函数实例代码详解的详细内容。
其它类似信息

推荐信息