首頁  >  文章  >  web前端  >  JavaScript強化教程 —— 物件建立模式

JavaScript強化教程 —— 物件建立模式

高洛峰
高洛峰原創
2016-10-15 17:05:16927瀏覽

介紹

本篇主要是介紹創建物件方面的模式的下篇,利用各種技巧可以極大地避免了錯誤或者​​可以編寫出非常精簡的程式碼。

模式:函數語法糖

函數語法糖是為一個物件快速添加方法(函數)的擴展,這個主要是利用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


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn