'this' keyword in built in functions [duplicate] - javascript

This question already has answers here:
What is the difference between string primitives and String objects in JavaScript?
(12 answers)
Are strings objects? [duplicate]
(6 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 4 years ago.
I don't quite understand how does the 'this' keyword in built-in functions like String, Number, etc point to the primitive value directly instead of the object like the 'this' keyword is supposed to. Is it just directly set by javascript engine?
I have this example:
String.prototype.repeatify = function(times) {
console.log(this); // Output - String {"hello"}
var str = "";
for(var i=0; i<times; i++) {
str += this; //how does 'this' gets set to 'hello' and not the object- String{ }??
}
return str;
}
var string = new String('hello');
console.log(string.repeatify(3)); //Output - prints hellohellohello
I was expecting the output in the chrome devtools to be [object Object][object Object][object Object]

There's a lot to this, but it's essentially the target of the function invocation.
Some examples:
String.prototype.whatever = function() {
return this + ' ugh.. whatever.'
// `this` is the string this method is called against
}
Array.prototype.slip = function() {
return ['Hellooo', ...this];
// `this` is the array in which the function is invoked on
}
function doSomething() {
console.log(this + ' something');
// `this` is whatever the function is bound to
}
console.log('Excuse me'.whatever()) // Excuse me ugh.. whatever.
console.log([1, 2, 3].slip()) // ["Hellooo", 1, 2, 3]
// In this case, the string 'I will do' becomes `this` in the doSomething function above as it's explicitly bound
doSomething.bind('I will do')(); // I will do something

var string = 'hello'; // ------------
// this refers to the |
// ----------v--string itself => 'hello'
console.log(string.repeatify(3));
You're defining repeatify on String prototype so this is just a type of String. Thus, it will log hellohellohello.

Related

Why is the "this" value different? [duplicate]

This question already has answers here:
JavaScript object functions and `this` when unbound and returned in expression/parens
(2 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 4 years ago.
Here is an example where o.foo(); is 3 but (p.foo = o.foo)(); is 2?
function foo() {
console.log( this.a );
}
var a = 2;
var o = { a: 3, foo: foo };
var p = { a: 4 };
o.foo(); // 3
(p.foo = o.foo)(); // 2”
If I do something like this then I get 4 which is what I want. How are those 2 examples are different?
p.foo = o.foo;
p.foo(); // 4
This :
(p.foo = o.foo)();
Is pretty much the same as doing this:
d = (p.foo = o.foo);
d();
Basically what it says is that the return of an assignment is the function itself in the global context. On which a is 2.
actually your code is wrong because your snippet doesnt run, you should be doing the following: console.log( this.a );
and now, lets see how this works.
function foo() {
console.log( this.a );
}
this will call this in the scope of the caller, so lets investigate our results.
so, you are setting a=2 globally, and then in the objects o.a = 3 and p.a=4
so:
calling o.foo it will return 3 because this is pointing to o
calling p.foo it will return 4 because this is pointing to p
BUT
calling (p.foo = o.foo)(); it will return 2 because it is not pointing to any object, so it will take your scope (which is the global scope) and then it will return 2.
if you go with:
p.foo = o.foo
p.foo() //4
it will return 4 successfully because it is pointing to p.
Performing that assignment operation before the function call here:
(p.foo = o.foo)();
causes the object reference to p to be lost. If you instead wrote
p.foo = o.foo;
p.foo();
you'd get 4. As it is, you get 2 because the value of this will be window in the function.
Because that parenthesized subexpression is an assignment result, there's no object lookup directly associated with the result of the expression — the value of the assignment expression is just the function reference without a contextual object. Thus the runtime doesn't have a value to use for this when it calls the function, so this is bound by default to window (or the global object in whatever context).

Reassigning objects within function [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 5 years ago.
I've noticed things like this work:
let x = { a: 1 };
function reassignProperty(obj, key, newValue) {
obj[key] = newValue;
}
reassignProperty(x, "a", "hello");
console.log(x.a); //prints hello
But this doesn't:
function reassignObject(obj) {
obj = { a: "some new value" };
}
reassignObject(x);
console.log(x.a); //still prints hello
It seems you can reassign properties of an object (pointers within an object), even if the values are reference types themselves. i.e. we could do things like reassignProperty(x, "a", { inner: 55 }), and it will still be the same outside the function scope. But reassigning the reference to the object itself doesn't?
I've seen people argue javascript passes variables into functions by value, but not by reference. Why then does it seem to able to reassign the properties inside the object, and have access to the changes outside the function scope? This doesn't seem to me to be strictly "pass by value"
In the second case use dot notation instead of object literal
let x = {
a: 1
};
function reassignObject(obj) {
console.log("Passed from function call ", obj);
if (obj.hasOwnProperty('a')) {
obj.a = "some new value"
}
console.log("After reassinging value ", obj)
}
reassignObject(x);
console.log(x.a);

Override print representation of a JavaScript array [duplicate]

This question already has answers here:
Does console.log invokes toString method of an object?
(4 answers)
How do I override the default output of an object?
(2 answers)
Closed 5 years ago.
I'm trying to take an array object and change its print representation - just of that object, not of all arrays in the program. I hoped setting the toString property would do the job, but it doesn't:
var a = [1, 2, 3]
// Prints using the default representation
console.log(a)
// Try to override toString
a.toString = function() {
return 'some new representation'
}
// Still uses the default representation
console.log(a)
What am I missing?
var a = [1, 2, 3];
// Prints using the default representation
console.log(a);
// Try to override toString
a.toString = function() {
return 'some new representation'
}
// append blank string to invoke toString function
console.log(""+a);

No colon after property name in object declaration, is it valid? [duplicate]

This question already has answers here:
How does this object method definition work without the "function" keyword?
(2 answers)
Closed 6 years ago.
I entered this expression in the Firefox and Chrome Dev Console and I wonder why it is valid JavaScript:
var x = { a (b) {} };
console.log(x);
x is then set to an object with the property "a" containing a function called "a" with an argument identifier "b".
How is this valid JavaScript syntax? The colon is missing after "a" and I do not understand the function definition.
This is ES6 / ES2015 syntactic sugar (Property shorthand).
With ES6:
const obj = {
a(b) {
// Shorthand method
// `this` context is `obj`
},
c
};
is equal to
var obj = {
a: function a(b) {
},
c: c
};
In JavaScript, when you write:
var x = { a (b) {} };
It will consider it as:
var x = {
a: function (b) {
}
}
For example, you can check this and it will clear your doubt:
var x = { a (b) { console.info('function called') } };
x.a();
This will call the function which is assigned to property a of object x.

Can you evaluate a property name within a JS object? [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I know that you can evaluate the value of a property inside of a JS object, like the following:
let object = {
value: 5+5
};
I am wondering if there is any possible way to evaluate the name of an attribute with JS, i.e. achieve the following:
let object;
object[5+5].value = "ten";
As something like:
let object = {
5+5: "ten"
};
Yes in ES2015, no in ES5, but first let's clear one thing up: that's JavaScript, not JSON.
In ES2015 (formerly known as ES6):
var something = "foo";
var object = {
[something]: "bar";
};
alert(object.foo); // "bar"
Inside the [ ] can be any expression you like. The value returned is coerced to a string. That means you can have hours of fun with stuff like
var counter = function() {
var counter = 1;
return function() {
return counter++;
};
};
var object = {
["property" + counter()]: "first property",
["property" + counter()]: "second property"
};
alert(object.property2); // "second property"
JSON is a serialization format inspired by JavaScript object initializer syntax. There is definitely no way to do anything like that in JSON.
Sure. Try this:
'use strict';
let object = {
[5+5]: "ten"
};
console.log(object); // Object {10: "ten"}

Categories