Object.create() JavaScript

时间:2016-02-12 20:53:27

标签: javascript oop object methods javascript-objects

I am quoting this statement from the JavaScript Definitive Guide book in section 6.1.4 Object.create(). The following statement doesn't seem clear to me.

You can pass null to create a new object that does not have a prototype, but if you do this, the newly created object will not inherit anything, not even basic methods like toString() (which means it won't work with the + operator either)

width

At this point, I was thinking "Oh Wow". It doesn't inherit any basic methods, when you set Object.create(null). So, I tried to give it a try on console to see if this was really the behavior. I ran the script that is below, and got an unexpected result.

var o2 = Object.create(null) // o2 inherits no props or methods.

When I ran this code, I was thinking that the .toString was not going to work. I am bit confused or may not understand how things are working here. I was wondering if anyone could clear things up for me. Any help will be appreciated, and thanks for the time for reading my problem. :)

3 个答案:

答案 0 :(得分:3)

array1 = np.array([[2,2],[3,2]]) array2 = np.array([0.3,3]) clf = GaussianNB() clf.fit(array1,array2) works in your example because you're running it on a number, not the object itself.

It works because it's no different than this:

toString

To see the results of no prototype, try this instead:

var n = 1;
console.log(n.toString());

答案 1 :(得分:2)

You're calling Hello ${user:-Guest} Here is your order ${order:-air} on the number property, which is not the object itself. If you were to try toString, it would not work.

答案 2 :(得分:2)

When you do ...

Waypoint

... you're creating a property named o2.number = 1 and adding that property to your number object.

When you do ...

o2

... you're executing o2.number.toString() not on toString, but on property o2.

If you do...

o2.number

... you'll see that console.log(typeof o2.number) has type o2.number, and thus has all methods associated with numbers.

If you do ...

number

... you'll see that console.log(typeof o2) has type o2.

If you try executing object, you'll get an error and see that this object indeed doesn't have any method named o2.toString.


Note :

In my experience, you probably don't ever want to do something like ...

toString

What you probably want instead, is something like ...

var o2 = Object.create(null);
o2.number = 1;

... which can can be written more elegantly like ...

var o2 = Object.create(Object.prototype);
o2.number = 1;

There is little to no advantage with creating objects that do not inherit from var o2 = { number : 1 }; . And if other people end up using your code, you're likely to confuse the heck out of other developers when they're trying to call eg. Object.prototype or hasOwnProperty on your object and they're getting an error (as they these methods expect to exist for any object).