1

var d = {};
d.a = 'myString';
d.b = function(a) {
    console.log(this);
}

d.b.call(d.a);

In the above code, why does 'myString' show as an object when it's logged to the console?

Even typeof shows it's an object. And with each alphabet split.

I was trying to do

arr = ['myString','foo','bar']
console.log(arr.includes(this));

and that returns false as well. How can I get it as a string when using this?

enter image description here

1
  • Works in JS fiddle for me Commented Jun 20, 2021 at 14:50

1 Answer 1

5

This is because your script is running in non-strict mode. If you add "use strict", then it works like you expect:

"use strict";

let d = {
    a: 'myString',
    b: function(a) {
        console.log(this);
    }
};

d.b.call(d.a);

The reason is that before ES6, this always was an object. Any primitive would be converted to an object. This is still the behaviour if you are not running in strict mode.

If it is not possible to put your whole script in strict mode, then just apply it to the function:

let d = {
    a: 'myString',
    b: function(a) {
        "use strict";
        console.log(this);
    }
};

d.b.call(d.a);

Sign up to request clarification or add additional context in comments.

2 Comments

This solved the problem. However, I can see that placing 'use strict' at the beginning of the page will require me to make a ton of changes. I hope it's ok to use it at function level then.
Yes, you can please "use strict" as the first line in the body of function b, and it will make the function behave according to strict mode rules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.