Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Object([]); do?

On a couple of polyfill examples in MDN for some Array prototype functions, there are the following two lines (e.g.: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find):

var list = Object(this);
var length = list.length >>> 0;

I presume the first example is autoboxing(?). But what is its purpose either way if this is always going to be an array anyway?

And line 2, how does this differ to:

var length = list.length || 0;

Thanks!

like image 608
keldar Avatar asked May 26 '15 10:05

keldar


People also ask

What does object in Java do?

A Java object is a member (also called an instance) of a Java class. Each object has an identity, a behavior and a state. The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects are created at runtime from templates, which are also known as classes.

What does an object do in OOP?

Objects are designed to share behaviors and they can take on more than one form. The program will determine which meaning or usage is necessary for each execution of that object from a parent class, reducing the need to duplicate code. A child class is then created, which extends the functionality of the parent class.

What does an object in python do?

Python object() Function The object() function returns an empty object. You cannot add new properties or methods to this object. This object is the base for all classes, it holds the built-in properties and methods which are default for all classes.

What is the role of object in class?

an object is an element (or instance) of a class; objects have the behaviors of their class. The object is the actual component of programs, while the class specifies how instances are created and how they behave.


1 Answers

This makes it possible to call the function (using call or apply) in strict mode on something which isn't an array while following the specification.

If it's an instance of Array, or an array-like object, it changes nothing.

But here, as this line ensuring list is an object follows a check that this is neither null or undefined, and as other values wouldn't make the following accesses fail (apart very special cases that Object(this) wouldn't solve, like failing accessors), I'm not sure there's really a point. Maybe it was set before the check, or maybe it's here just in case of special native objects. Another possibility is that it (too?) strictly follows the specification step by step and wants to apply toObject.

list.length >>> 0 is better than || 0 in the fact it rounds to the nearest lower positive integer (in a 32 bits range). I'm not sure why >> wasn't used here, as it doesn't seem to be better to iterate until 4294967295 rather than to -1 (i.e. don't lose time).

like image 99
Denys Séguret Avatar answered Sep 30 '22 20:09

Denys Séguret