Skip to content Skip to sidebar Skip to footer

Why Do New And Object.create Behave Differently In This Example

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=Obje

Solution 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 = functionfoobar() {},
    ex = Object.create(test);
ex.name; // "foobar"

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

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

This pattern is not guaranteed to work with DOM constructors.

Solution 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= newtest("AAA");
test1.name;//AAAvar test2=Object.create(test);
test2.name2="AAA";
typeof(test2);//Objectconsole.log(test2.name2);//"AAA"

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

Post a Comment for "Why Do New And Object.create Behave Differently In This Example"