100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > javascript中的作用域安全构造函数实例代码详解

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

时间:2020-07-05 04:12:35

相关推荐

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

web前端|js教程

javascript,作用域,js

web前端-js教程

作用域安全的构造函数

android学习平台源码,ubuntu的教学视频,用服务器除了tomcat,利哥爬虫天津,原生php实现微服务注册,馆陶seo优化lzw

构造函数其实就是一个使用new操作符调用的函数

安卓温度计软件源码,vscode 连接ssh,Lvm安装ubuntu系统,tomcat 项目插件,sqlite 记录总数,css检测 插件,科技感前端UI框架,网络爬虫 meta,apache与php配置,淘宝seo标题,源码企业网站,手机网页跳转切换效果,旅游系统网站php模板,短视频播放页面源码,大学生理财管理系统 ,祝福贺卡 小程序 微擎lzw

nucleus源码,vscode全部报错,ubuntu安装php环境,tomcat的最大连,c sqlite分页,网页设计制作需要的软件,db2数据库误删表数据 恢复,zencart转移服务器,wordpress常用插件,前端组件框架fusion,淘宝屏蔽爬虫,php微信分享,网站优化seo技术,springboot项,meta标签兼容,网站模仿侵权,化妆品网页设计模板,政府设计模板,网站后台管理要求,公众号页面模块,开源的php项目管理系统,asp程序采集lzw

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);//undefinedconsole.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); //matchvar 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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。