Search This Blog

2026/08/08

Javascript : Guess output of the code



Guess output of the code.

Code:
//first question
var obj = {
    a: 1,
    b: 2,
    add: function () {
        return this.a + this.b;
    }
}
var r = obj.add();
console.log("r=" + r);

//second question
var obj1 = {
    a: 1,
    b: 2,
    add: function () {
        return this.a + this.b;
    }
}
var s = obj1.add;
console.log("s=" + s());

//third question
var s1 = obj1.add;
s2 = s1.bind(obj1);
console.log("s2=" + s2());

Output:
        r=3
        s=NaN
s2=3


Notes:
wrt obj1.add here s contains the function, but the connection
to obj1 is not retained.In non-strict mode, JavaScript sets: this = globalThis

No comments:

Post a Comment