您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

JavaScript强化教程 —— 对象创建模式

2024/4/17 8:18:52发布8次查看
介绍
本篇主要是介绍创建对象方面的模式的下篇,利用各种技巧可以极大地避免了错误或者可以编写出非常精简的代码。
模式:函数语法糖
函数语法糖是为一个对象快速添加方法(函数)的扩展,这个主要是利用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
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录