JSFiddle - React, Tailwind, and code Playground
by Chuan Shao
JavaScript
var x = 99;
var sample = {
x:1,
act:function(a){
this.x = a*a;//assign value to sample's x, not global object's x.
}
}
sample.act(6);
console.log(sample.x);//36
console.log(x);//99
//other ways to invoke method
sample["act"](7);
console.log(sample.x);//49
//nested function can access variable outside of it.
var y = 88;
var sample2 = {
y:1,
act2:function(a){
this.y = inner();
function inner(){
return a*a;
}
}
}
sample2.act2(8);
console.log(sample2.y);//64
console.log(y);//88
//nested function does not inherit "this". The "this" in nested function is global object
var sample3 = {
act3:function(){
inner();
function inner(){
console.log(this);//window object
}
}
}
sample3.act3();
//pass "this" to nested function
var sample4 = {
act4:function(){
var self = this;
inner();
function inner(){
console.log(self);//Object {act4=function()}
}
}
}
sample4.act4();