Why do new and object.create behave differently in this example

耗尽温柔 提交于 2019-12-11 16:53:33

问题


In this simple example, why do new and Object.create behave differently?

var test=function(name){
    this.name=name
};
var test1= new test("AAA");
test1.name;//AAA

var test2=Object.create(test);
test2.name="AAA";
typeof(test2);//Object
test2.name;//"" (empty string).

Why is test2.name empty?


回答1:


Object.create expects an Object as it's first argument for the prototype chain, not a function (or constructor in your case).

It won't complain if you pass a function, but it means that certain extra things will be inherited by your created Object, for example, the non-writability of function names.

The reason you're getting an empty string is because test is an anonymous function, so test.name is "". As I said above, this is non-writable, so

test.name = 'foo';
test.name; // still ""

If you had used a named function expression for test, this would have been more obvious.

var test = function foobar() {},
    ex = Object.create(test);
ex.name; // "foobar"

EDIT a function that behaves like new for test using Object.create would look like this

function myNew() {
    var o = Object.create(test.prototype); // set up prototype inheritance
    test.apply(o, arguments);              // then construct
    return o;
}
// and using it
var test3 = myNew('AAA');
test3.name; // "AAA"
test3.name = 'BBB';
test3.name; // "BBB"

This pattern is not guaranteed to work with DOM constructors.




回答2:


The word "name" is "almost reserved" in JavaScript. If you try a normal attribute name, it should work. For example,

var test=function(name){this.name=name};
var test1= new test("AAA");
test1.name;//AAA
var test2=Object.create(test);
test2.name2="AAA";
typeof(test2);//Object
console.log(test2.name2);//"AAA"

For difference between the two ways of creating objects, this page shows some examples with explanation.



来源:https://stackoverflow.com/questions/17245580/why-do-new-and-object-create-behave-differently-in-this-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!