深入理解JavaScript系列(48):对象创建模式(下篇)

2024-09-01 15:32

本文主要是介绍深入理解JavaScript系列(48):对象创建模式(下篇),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

介绍

本篇主要是介绍创建对象方面的模式的下篇,利用各种技巧可以极大地避免了错误或者可以编写出非常精简的代码。

模式6:函数语法糖

函数语法糖是为一个对象快速添加方法(函数)的扩展,这个主要是利用prototype的特性,代码比较简单,我们先来看一下实现代码:

if (typeof Function.prototype.method !== "function") {Function.prototype.method = function (name, implementation) {this.prototype[name] = implementation;return this;};
}

扩展对象的时候,可以这么用:

var Person = function (name) {this.name = name;
}
.method('getName',function () {return this.name;})
.method('setName', function (name) {this.name = name;return this;
});

这样就给Person函数添加了getName和setName这2个方法,接下来我们来验证一下结果:

var a = new Person('Adam');
console.log(a.getName()); // 'Adam'
console.log(a.setName('Eve').getName()); // 'Eve'

模式7:对象常量

对象常量是在一个对象提供set,get,ifDefined各种方法的体现,而且对于set的方法只会保留最先设置的对象,后期再设置都是无效的,已达到别人无法重载的目的。实现代码如下:

var constant = (function () {var constants = {},ownProp = Object.prototype.hasOwnProperty,// 只允许设置这三种类型的值allowed = {string: 1,number: 1,boolean: 1},prefix = (Math.random() + "_").slice(2);return {// 设置名称为name的属性set: function (name, value) {if (this.isDefined(name)) {return false;}if (!ownProp.call(allowed, typeof value)) {return false;}constants[prefix + name] = value;return true;},// 判断是否存在名称为name的属性isDefined: function (name) {return ownProp.call(constants, prefix + name);},// 获取名称为name的属性get: function (name) {if (this.isDefined(name)) {return constants[prefix + name];}return null;}};
} ());

验证代码如下:

// 检查是否存在
console.log(constant.isDefined("maxwidth")); // false// 定义
console.log(constant.set("maxwidth", 480)); // true// 重新检测
console.log(constant.isDefined("maxwidth")); // true// 尝试重新定义
console.log(constant.set("maxwidth", 320)); // false// 判断原先的定义是否还存在
console.log(constant.get("maxwidth")); // 480

模式8:沙盒模式

沙盒(Sandbox)模式即时为一个或多个模块提供单独的上下文环境,而不会影响其他模块的上下文环境,比如有个Sandbox里有3个方法event,dom,ajax,在调用其中2个组成一个环境的话,和调用三个组成的环境完全没有干扰。Sandbox实现代码如下:

function Sandbox() {// 将参数转为数组var args = Array.prototype.slice.call(arguments),// 最后一个参数为callbackcallback = args.pop(),// 除最后一个参数外,其它均为要选择的模块modules = (args[0] && typeof args[0] === "string") ? args : args[0],i;// 强制使用new操作符if (!(this instanceof Sandbox)) {return new Sandbox(modules, callback);}// 添加属性this.a = 1;this.b = 2;// 向this对象上需想添加模块// 如果没有模块或传入的参数为 "*" ,则以为着传入所有模块if (!modules || modules == '*') {modules = [];for (i in Sandbox.modules) {if (Sandbox.modules.hasOwnProperty(i)) {modules.push(i);}}}// 初始化需要的模块for (i = 0; i < modules.length; i += 1) {Sandbox.modules[modules[i]](this);}// 调用 callbackcallback(this);
}// 默认添加原型对象
Sandbox.prototype = {name: "My Application",version: "1.0",getName: function () {return this.name;}
};

然后我们再定义默认的初始模块:

Sandbox.modules = {};Sandbox.modules.dom = function (box) {box.getElement = function () {};box.getStyle = function () {};box.foo = "bar";
};Sandbox.modules.event = function (box) {// access to the Sandbox prototype if needed:// box.constructor.prototype.m = "mmm";box.attachEvent = function () {};box.detachEvent = function () {};
};Sandbox.modules.ajax = function (box) {box.makeRequest = function () {};box.getResponse = function () {};
};

调用方式如下:

// 调用方式
Sandbox(['ajax', 'event'], function (box) {console.log(typeof (box.foo));// 没有选择dom,所以box.foo不存在
});Sandbox('ajax', 'dom', function (box) {console.log(typeof (box.attachEvent));// 没有选择event,所以event里定义的attachEvent也不存在
});Sandbox('*', function (box) {console.log(box); // 上面定义的所有方法都可访问
});

通过三个不同的调用方式,我们可以看到,三种方式的上下文环境都是不同的,第一种里没有foo; 而第二种则没有attachEvent,因为只加载了ajax和dom,而没有加载event; 第三种则加载了全部。

模式9:静态成员

静态成员(Static Members)只是一个函数或对象提供的静态属性,可分为私有的和公有的,就像C#或Java里的public static和private static一样。

我们先来看一下公有成员,公有成员非常简单,我们平时声明的方法,函数都是公有的,比如:

// 构造函数
var Gadget = function () {
};// 公有静态方法
Gadget.isShiny = function () {return "you bet";
};// 原型上添加的正常方法
Gadget.prototype.setPrice = function (price) {this.price = price;
};// 调用静态方法
console.log(Gadget.isShiny()); // "you bet"// 创建实例,然后调用方法
var iphone = new Gadget();
iphone.setPrice(500);console.log(typeof Gadget.setPrice); // "undefined"
console.log(typeof iphone.isShiny); // "undefined"
Gadget.prototype.isShiny = Gadget.isShiny;
console.log(iphone.isShiny()); // "you bet"

而私有静态成员,我们可以利用其闭包特性去实现,以下是两种实现方式。

第一种实现方式:

var Gadget = (function () {// 静态变量/属性var counter = 0;// 闭包返回构造函数的新实现return function () {console.log(counter += 1);};
} ()); // 立即执行var g1 = new Gadget(); // logs 1
var g2 = new Gadget(); // logs 2
var g3 = new Gadget(); // logs 3

可以看出,虽然每次都是new的对象,但数字依然是递增的,达到了静态成员的目的。

第二种方式:

var Gadget = (function () {// 静态变量/属性var counter = 0,NewGadget;//新构造函数实现NewGadget = function () {counter += 1;};// 授权可以访问的方法NewGadget.prototype.getLastId = function () {return counter;};// 覆盖构造函数return NewGadget;
} ()); // 立即执行var iphone = new Gadget();
iphone.getLastId(); // 1
var ipod = new Gadget();
ipod.getLastId(); // 2
var ipad = new Gadget();
ipad.getLastId(); // 3

数字也是递增了,这是利用其内部授权方法的闭包特性实现的。

这篇关于深入理解JavaScript系列(48):对象创建模式(下篇)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1127333

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

认识、理解、分类——acm之搜索

普通搜索方法有两种:1、广度优先搜索;2、深度优先搜索; 更多搜索方法: 3、双向广度优先搜索; 4、启发式搜索(包括A*算法等); 搜索通常会用到的知识点:状态压缩(位压缩,利用hash思想压缩)。