作用域安全的构造函数
构造函数其实就是一个使用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);//matchwindow的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()会创建并返回一个新的实例
PHP网络编程技术详解由浅入深,全面、系统地介绍了PHP开发技术,并提供了大量实例,供读者实战演练。另外,笔者专门为本书录制了相应的配套教学视频,以帮助读者更好地学习本书内容。这些视频和书中的实例源代码一起收录于配书光盘中。本书共分4篇。第1篇是PHP准备篇,介绍了PHP的优势、开发环境及安装;第2篇是PHP基础篇,介绍了PHP中的常量与变量、运算符与表达式、流程控制以及函数;第3篇是进阶篇,介绍
386
立即学习“Java免费学习笔记(深入)”;
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中的作用域安全构造函数实例代码详解的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号