js中类和函数都要经过function关键字来构建。javascript
function Foo(name, age) { this.name = name; this.age = age; this.getName = function () { console.log(this.name) } } obj = new Foo('文州', 19); // 实例化一个对象 obj.getName(); // 输出:文州
function test() { console.log(this); } // 等同于window.test,所以这里的this代指的是window test(); // 输出:Window
自执行函数,同上面等价,this也是代指的window。java
(function () { console.log(this); // 输出:Window })()
var name = '景女神'; function Foo(name, age) { this.name = name; this.age = age; this.getName = function () { console.log(this.name); // 文州 (function () { console.log(this.name); // 景女神(打印的外部全局变量) })() } } obj = new Foo('文州', 19); obj.getName(); // 文州 景女神
生成对象后,对象执行getName方法,此时this.name是输出的当前对象的name,所以是输出文州。随后再执行自执行函数,这里的this指代的是window对象,获取全局name变量,所以输出景女神。函数
var name = '景女神'; function Foo(name, age) { this.name = name; this.age = age; this.getName = function () { console.log(this.name); // 文州 var that = this; (function () { console.log(that.name); // 文州(打印的外部全局变量) })() } } obj = new Foo('文州', 19); obj.getName(); // 文州 文州
obj = { name: '文州', age: 19, getName:function () { console.log(this.name); // 文州 var that = this; (function () { console.log(that.name); // 文州 })() } } obj.getName();