JS的设计模式
来源:互联网 发布:联通语音网络类型 编辑:程序博客网 时间:2024/06/04 01:26
- 工厂模式:在一个函数中创建一个对象,并赋予这个对象属性和方法
例如:function factory(name, job) { var o = new Object(); o.name = name; o.job = job; o.sayName = function () { console.log(this.name); }; return o;}var factory1 = factory("suning", "worker");
- 构造函数模式:创建实例,通过this指定属性和方法,没有返回值,再通过new调用
例如:function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function () { console.log(this.name); };}var person1 = new Person("Lucy", 22, "worker");
- 原型模式:主要是先创建一个原型对象,再使用prototype原型链来继承
例如:function Person() {}Person.prototype.name = "Lucy";Person.prototype.age = 30;Person.prototype.job = "worker";Person.prototype.sayName = function () { console.log(this.name);};var person1 = new Person();
- 组合模式:使用构造函数定义属性,使用原型模式定义方法和共享的属性,构造函数和原型分开
例如:function Person(name, age, job) { this.name = name; this.age = age; this.job = job;}Person.prototype = { constructor: Person, sayName: fucntion () { console.log(this.name); }}var person1 = new Person("Lucy", 30, "worker");
- 动态原型链模式:检查某个方法是否有效,来初始化原型,原型在构造函数的内部
例如:function Person(name, age, job) { this.name = name; this.age = age; this.job = job; if(typeof this.sayName != "function") { Person.prototype.sayName = function () { console.log(this.name); }; }}var friend = new Person("Lucy", 30, "worker");
- 寄生构造函数模式:在使用工厂模式创建的构造函数中创建对象,并使用new初始化
例如:function Person(name, age, job) { var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function () { console.log(this.name); }; return o;}var friend = new Person("Lucy", 40, "worker");
- 稳妥构造函数模式:不使用this和new的构造函数
例如:function Person(name, age, job) { var o = new Object(); o.sayName = function () { console.log(name); }; return o;}var friend = Person("Lucy", 30, "worker");
掌握原型链对于理解JS的设计模式至关重要:
阅读全文
0 0
- JS的设计模式
- 常用的JS设计模式
- js设计模式的学习
- js常用的设计模式
- 【设计模式】JS中常见的设计模式
- 几种js设计模式的理解
- js中常用的设计模式
- js的36个设计模式:前奏
- 转载:js版本的设计模式
- JS设计模式
- js设计模式
- js 设计模式 参考
- js设计模式
- JS设计模式
- js设计模式
- JS设计模式 零
- JS设计模式 零
- JS设计模式 零
- 对线性回归、逻辑回归、各种回归的概念学习
- MySQL 学习随笔
- C++笔试题(十五).富途证券 & 猎豹移动 & TP-LINK
- 【STL】容器调用时机
- Uva10791 质因数分解
- JS的设计模式
- 【STL】常用算法
- sdnu1007
- Visual Studio 2017 编译器的安装与最基本使用
- Python-设计模式
- 692. Top K Frequent Words
- 改造HelloWorld项目
- MTS与MTO浅析
- 对JAVA代码设计六大原则的理解