Domanda

So I'm extending some native JS objects and noticed some oddities when it comes to this. When I log this on strings, I notice it's an array-like object which also has a property called [[PrimitiveValue]] which contains the value the value I'd expect, but cannot be retrieved using a obj['[[PrimitiveValue]]'] syntax.

Take this example:

String.prototype.method = function() {
  return this;
};

Number.prototype.method = function() {
  return this;
};

var str = "12";
var num = 12;

console.log( str.method() );
console.log( num.method() );

Wanting to get the actual value, I tried something like this however it gets logged as undefined:

String.prototype.method = function() {
  return this['[[PrimitiveValue]]'];
};

Number.prototype.method = function() {
  return this['[[PrimitiveValue]]'];
};

I noticed it was possible to get the raw value using some type conversion, however this feels really hackish. (this + 0 for Number, this + '' for String.)

So what type of object am I dealing with here? How do I effectively interact with this inside a native JS object's prototype?

È stato utile?

Soluzione

Those are just the native objects; you use this just like in a normal prototype function.

Note that you are indeed working with objects: instances built with the "String" or "Number" or some other native constructor. Things like "hello world" and 12.54 are not objects, they're primitives. They don't have prototypes.

When you use a primitive object as if it were an object, the runtime automatically promotes it to an object instance. That happens when you use a primitive value with the . or [] operators.

From such objects (instances of String, Number, or Boolean), the primitive value can be fetched with this.valueOf().

Altri suggerimenti

In the String prototype, this refers to String object type. It has the length property, but it is not a real array, it an is array-like object. You can access the this value at subscripts like this[0] an so forth, but to convert it an array so you can use methods such as forEach and all the other prototype methods of the Array, you may do var args = Array.prototype.call(this); For example let's illustrate this:

String.prototype.hello = function() {
  console.log(this);
  console.log(typeof this);
  console.log(Object.getOwnPropertyNames(this));    
}
"adfadfda".hello();

To get the full string as called on the hello method, you can use this.toString(); which would return in this case "adfadfda"

enter image description here

To actually see the type of object that the this value represents we can do:

Object.prototype.toString.call(this);

Which would return:

[object String]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top