假设您正在创建数据类型并公开其行为。
你能举一些你什么时候使用的例子:
一个功能和新的:
// define new data type var CustomDataType= function(){ this.a='whatever'; this.doX= function(){/*some code*/}; } // create a new instance of our custom data type var obj= new customDataType();
对象文字和 Object.create:
// define new data type var customDataType = { a: 'whatever', doX: function(){/*some code*/} } // create a new instance of our custom data type var obj= Object.create(customDataType);
构建对象的函数:
function customDataTypeFactory(options){ return { a: 'whatever', doX: function(){/*some code*/} } }; // create a new instance of our custom data type var obj= customDataTypeFactory(options);
我觉得这可以被标记为重复:new
vs Object.create
,但我的主要兴趣不是讨论哪个更好,而是要知道是否有特定的用例应该优先于其他用例。
我已经阅读了许多有关相关问题的帖子和 Crockford 的书:Javascript:好的部分。到目前为止,我已经得出结论,这是一个偏好问题,强硬的 Crockford 的建议对我产生了很大的共鸣:“尽量避免危险和不必要的功能”......我说的是new
.