global object and this

Javascript Basic

Global object is special object. all object is property of the Global object

function func(){
  alert('Hello?');
}
func();
window.func();

Window api
https://developer.mozilla.org/en-US/docs/Web/API/Window

in Web browser, global object is “Window”
but in node.js, global object is “global”

this means context in function, it can be changeable depending on the situation.

1 . function and this
call function

func is no object so it is belong to Window object so this is Window.

function func(){
  if(window === this){ // Window === this
    document.write("window === this");
  }
}
func();

2 . method and this

func is belong to object o, o belong to object Window. so this is object o.

var o = {
  func : function() {
    if(o === this){ // o === this
      document.write("o === this");
    }
  }
}

3 . constructor and this

var funcThis = null;

function Func(){
  funcThis = this;
}
// funcThis === null
var o1 = Func();  // call function
// funcThis === object Window
if(funcThis === window) {
  document.write('window </br>');
}
var o2 = new Func(); // call constructor
// funcThis === Object o2
if(funcThis === o2) {
  document.write('o2 </br>');
}

4 . apply and this

var o = {}
var p = {}
function func(){
  switch(this){
    case o:
      document.write('b<br />');
      break;
    case p:
      document.write('p<br />');
      break;
    case window:
      document.write('window<br />');
      break;
  }
}
func(); // Window
func.apply(o); // o
func.apply(p); // p

Continue reading

constructor and new

Javascript Basic

Javascript is Prototype-based programming.

Object declaration

two ways to create a object

1.

var person = {} // Object
person.name = 'euido'; // name : Property
person.introduce = function(){ // introduce : Method
  return 'My name is '+this.name;
}
document.write(person.introduce());

2.

var person = {
  'name' : 'euido',
  'introduce' : function(){
    return 'My name is ' + this.name;
  }
}
document.write(person.introduce());


Constructor

function Person(){}
var p = new Person(); // Constructor
p.name = 'euido';
p.introduce = function(){
  return 'My name is '+this.name;
}

if we type like this

function Person(){}
var p0 = Person(); // p0 = undefined

but if we use “new”,

function Person(){}
var p0 = new Person(); // p0 = person{}

in Javascript, constructor is just function not belong to any no concept like class in java.

to re-use an object, we can express like..

// initialize object
function Person(name){
  this.name = name;
  this.introduce = function() {
    return 'My name is ' + this.name;
  }
}
var p1 = new Person('euido');
document.write(p1.introduce()+"<br />");

var p2 = new Person('leezche');
document.write(p2.introduce());

Continue reading

Pagination


© 2017. by isme2n

Powered by aiden