JavaScript patterns simplified--javascript模式

Adapter Design Pattern in C#

介绍

JavaScript语言存在自1995(如果我没记错的话),它是Web客户端开发的一个选择性语言。开始写javascript代码非常简单,但成为一个专家是不容易的。其中一个原因是,JavaScript是一个动态的语言,因为有多种方法来做同样的事情。写一份套管代码,使得它以后很难维护。

使任何一个语言更易维护的是使用设计模式,JavaScript代码的方式也不例外。很有多文章描述JavaScript模式。我觉得把它们列出在一个地方,并提供了一个简短的说明是一个好主意。

JavaScript4种基本模式

原型模式

组件模式

显示模块模式

揭示原型模式

Prototype pattern

.利用固有的JavaScript功能

.由一个构造函数和一个原型

.提供扩展能力

.在所有实例中共享对象的属性,包括所有的“私人”的变量。

// Define a class like this
function Person(name) {
   // Add object properties like this
   this.name = name;
}
// Add methods like this.  All Person objects will be able to invoke this
Person.prototype.speak = function() {
    alert('Hi, my name is ' + this.name);
}
// Instantiate new objects with 'new'
var person = new Person('John');
// Invoke methods like this
person.speak();

Module pattern

提供的变量和函数封装

提供了一种方法来增加 (公共或私人的)成员

每个对象实例在内存中创建新的副本的功能

扩展对象可以是困难,因为没有使用原型设计

// Define a class like this
function Person() {
    // Add methods like this. This is a private method
    var speak = function speak(name) {
        alert('Hi, my name is ' + name);
    }
    
    // Return public methods when this object is instantiated. All Person objects will be able to invoke this
    return {
        say: speak
      };
}
// Instantiate new objects with 'new'
var person = new Person();
// Invoke methods like this
person.say('John');
person.speak('John'); // undefined

Revealing Prototype pattern

提供的变量和函数封装

结合原型模式和显示模块模式最好的部分

提供了一种方法来增加(公共或私人的)成员

提供扩展能力

// Define a class like this
function Person(name) {
   // Add object properties like this
   this.name = name;
}
// Add methods like this.  All Person objects will be able to invoke this
Person.prototype.speak = function() {
    alert('Hi, my name is ' + this.name);
}
// Instantiate new objects with 'new'
var person = new Person('John');
// Invoke methods like this
person.speak();

Revealing Module pattern

提供的变量和函数封装

提供了一种方法来增加(公共或私人的)成员

清洁的方式来揭露公共成员相比,组件模式

扩展对象困难因为没有使用的原型设计

// Define a class like this
function Person() {
    // Add methods like this. This is a private method
    var speak = function speak(name) {
        alert('Hi, my name is ' + name);
    }
    
    // Return public methods when this object is instantiated. All Person objects will be able to invoke this
    return {
        say: speak
      };
}
// Instantiate new objects with 'new'
var person = new Person();
// Invoke methods like this
person.say('John');
person.speak('John'); // undefined








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值