this in javascript

Something Like that:
this

For that you need to create first html code.

HTML

<p>Function a =  <span id="demo1"></span></p>
<p>Function b =  <span id="demo2"></span></p>
<p>Global =  <span id="demo3"></span></p>

After that add this JS code.

JS

function a(){
    document.getElementById("demo1").innerHTML = this;
    this.newvar = 'hello';
}
var b = function(){
    document.getElementById("demo2").innerHTML = this;
}
a(); //this will point window
document.getElementById("demo3").innerHTML = newvar;
b(); //this will point window

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”QMvvxP” default_tab=”result” user=”pradeepanvi”]See the Pen this in javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now you can see

Function a = [object Window]
Function b = [object Window]
Global = hello

We have another example

For that you need to create first html code.

HTML

<p>Update c =  <span id="demo1"></span></p>
<p>Update again c =  <span id="demo2"></span></p>

After that add this JS code.

JS

var c = {
    name: 'The c object',
    log: function(){
        var self = this;
        self.name = 'Updated c object';
        document.getElementById("demo1").innerHTML = self.name;

        var setname = function(newname){
            self.name = newname;
        }
        setname('Updated again! the c object');
        document.getElementById("demo2").innerHTML = self.name;
    }
}

c.log();

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”XaRRyd” default_tab=”result” user=”pradeepanvi”]See the Pen this in javascript 02 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now you can see

Update c = Updated c object
Update again c = Updated again! the c object

Leave a Reply

Your email address will not be published. Required fields are marked *