作用域安全的构造函数
来源:互联网 发布:90平装修多少钱知乎 编辑:程序博客网 时间:2024/05/18 03:55
一般的构造函数是这个样子的。
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; }var person1 = new Person("Nicholas", 29, "Software Engineer"); alert(person1.name); //"Nicholas" alert(person1.age); //29 alert(person1.job); //"Software Engineer"var person2 = Person("Nicholas", 29, "Software Engineer"); alert(person2); //undefined alert(window.name); //"Nicholas" alert(window.age); //29 alert(window.job); //"Software Engineer"
这样就有一个弊端,如果没有使用 new 关键字,会把属性添加到window上。所以更好的做法应该是这样子的
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); } }
如上所示就可以避免这个问题,所以推荐使用。但是,这个也有一个要特别注意的地方,因为他侧通过检测是不是Person的实例,所以继承的时候
必须使用原型链或者寄生组合,如下。
1、错误
function Polygon(sides){ if (this instanceof Polygon) { this.sides = sides; this.getArea = function(){ return 0; }; } else { return new Polygon(sides); } } function Rectangle(width, height){ Polygon.call(this, 2); this.width = width; this.height = height; this.getArea = function(){ return this.width * this.height; }; } var rect = new Rectangle(5, 10); alert(rect.sides); //undefined
2.正确
function Polygon(sides){ if (this instanceof Polygon) { this.sides = sides; this.getArea = function(){ return 0; }; } else { return new Polygon(sides); } } function Rectangle(width, height){ Polygon.call(this, 2); this.width = width; this.height = height; this.getArea = function(){ return this.width * this.height; }; } Rectangle.prototype = new Polygon(); var rect = new Rectangle(5, 10); alert(rect.sides); //2
0 0
- 作用域安全的构造函数
- 作用域安全的构造函数
- 作用域安全的构造函数
- js作用域安全的构造函数
- 作用域安全的构造函数
- 作用域安全的构造函数
- 作用域安全的构造函数
- JS高级编程5-作用域安全的构造函数
- 函数柯理化以及构建作用域安全的构造函数
- JavaScript之安全作用域的构造函数(高级函数)
- 作用域安全的构造函数以及js对象的创建步骤
- 构造函数的作用
- 构造函数的作用
- 构造函数的作用
- 构造函数的作用.
- 构造函数的作用
- javascript创建构造函数时作用域安全,即怎样保证一直都是构造函数
- 【构造函数】解析构造函数的作用
- 响应式表格(Bootstrap)
- 【leetcode】108. Convert Sorted Array to Binary Search Tree【java】
- MYSQL登录错误:mysqladmin: connect to server at "localhost" failed
- 单目深度估计(Monocular Depth Estimation)之摄像机运动对深度估计的影响
- 小白从Linux到放弃第六篇
- 作用域安全的构造函数
- WPF 资源字典样式引用导致的DependencyProperty.UnsetValue
- 获取一个数组中最长的连续的元素序列
- win10 uwp应用开发(JS)——wifi扫描连接
- 树、森林和二叉树的转换
- 摄影:一些好看的拍摄
- 反射
- Springmvc+mybatis案列 1
- Strick mode 和Trace View使用