JavaScript函数与面向对象

一、JS面向对象

function Func(name,age){
      //this = obj
  this.Name = name;
  this.Age = age;
}

obj = new Func('ray',18)            //new一个对象

二、this关键字

// 每个函数中都有this
// 函数调用时this就是window
// new对象调用时this就是obj

function func(){ 
     // this = window  
     console.log(this);
}
func();            //相当于 window.func()


function func(){ 
     // this = obj  
     console.log(this);
}
obj = new func();            

  

三、JavScript中没有字典,只有对象

Name = '张三'
obj = {
    Name = 'ray';
    Age = 18;
    Func = function(){
        // this = obj
        console.log(this.Name)       #ray
        function inner(){
            // this = window
            console.log(this.Name)
        }
        inner();             //相当于 window.inner();
    }  
}    

obj.Func()

四、总结:

① 每个函数都有this,谁调用this,this就是谁

② 如果是全局调用函数没有new,则this就是window;如果是对象obj = new func()调用,this则是obj对象