javasript this
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script> //场景1 //当定义的函数,没有被上级所调用,那么这个this代表window var test = function(){ var name = 'liu'; console.log(this); //windows 对象 alert(this.name); //空 } test(); //场景2 此处this 为 test1,可以直接访问对象属性 console.log(typeof([])); //type类型为object consoel.log(typeof({})) // type类型为object var test1 = { name: "liu", fn: function(){ console.log(this.name); //liu } } test1.fn(); //场景3 调用执行方法的对象为obj,所以这里this就是obj,自然可以访问到name,结果为obj.name //如果上层有多个层级对象,则this为离他最近的调用对象 var test2 = { name: "liu", obj:{ name: "obj.liu", fn: function(){ console.log(this.name); //obj.liu } } } test2.obj.fn(); </script> </head> <body> </body> </html>