这是道格拉斯·克罗克福德 (Douglas Crockford) 幻灯片中的原始资料:
function constructor(spec) {
let {member} = spec,
{other} = other_constructor(spec),
method = function () {
// member, other, method, spec
};
return Object.freeze({
method,
other
});
}
以下示例是 Douglas Crockford 2014 年对象创建模式的更具体版本。
Douglas Crockford 大量使用了 ECMAScript 6 功能,例如解构等!!
在 node.js 中使用以下选项启动代码(启用 ES6):
node --harmony --harmony_destructuring demo.js
demo.js
// Douglas Crockford 2014 Object Creation
(function() {
'use strict';
function adress(spec) {
let {
street, city
} = spec,
logAdress = function() {
console.log('Adress:', street, city);
};
return Object.freeze({
logAdress
});
};
function person(spec) {
let {
preName,
name
} = spec, {
logAdress
} = adress(spec),
logPerson = function() {
// member, other, method, spec
console.log('Name: ', preName, name);
logAdress();
};
return Object.freeze({
logPerson,
logAdress
});
};
let myPerson = person({
preName: 'Mike',
name: 'Douglas',
street: 'Newstreet',
city: 'London'
});
myPerson.logPerson();
})();
根据 Douglas Crockford 的谈话,他避免使用:
观看原始 Crockford 视频:
https://www.youtube.com/watch?v=PSGEjv3Tqo0
Crockford Douglas Object Creation Pattern 2014 的一个很好的解释是这个博客:https://weblogs.asp.net/bleroy/crockford%E2%80%99s-2014-object-creation-pattern