Tag: 对象创建

理解Object.create()和new SomeFunction()之间的区别

我最近偶然发现了JavaScript中的Object.create()方法,试图推导出它与使用new SomeFunction()创建对象的新实例的方式不同,以及何时想要使用另一个方法。 考虑下面的例子: var test = { val: 1, func: function() { return this.val; } }; var testA = Object.create(test); testA.val = 2; console.log(test.func()); // 1 console.log(testA.func()); // 2 console.log('other test'); var otherTest = function() { this.val = 1; this.func = function() { return this.val; }; }; var otherTestA = new otherTest(); var otherTestB = […]

使用“Object.create”而不是“新”

JavaScript 1.9.3 / ECMAScript 5引入了Object.create ,道格拉斯·克罗克福德(Douglas Crockford)等人长期以来一直主张 。 如何用Object.create替换下面的代码中的new ? var UserA = function(nameParam) { this.id = MY_GLOBAL.nextId(); this.name = nameParam; } UserA.prototype.sayHello = function() { console.log('Hello '+ this.name); } var bob = new UserA('bob'); bob.sayHello(); (假设存在MY_GLOBAL.nextId)。 我能想到的最好的是: var userB = { init: function(nameParam) { this.id = MY_GLOBAL.nextId(); this.name = nameParam; }, sayHello: function() { […]