一、js中function的不同形态
js中类和函数都要通过function关键字来构建。
1、js中当函数名大写时,一般是当作类来处理
function Foo(name, age) {
this.name = name;
this.age = age;
this.getName = function () {
console.log(this.name)
}
}
obj = new Foo('文州', 19); // 实例化一个对象
obj.getName(); // 输出:文州
2、js中函数名小写,当做函数来处理
function test() {
console.log(this);
}
// 等同于window.test,因此这里的this代指的是window
test(); // 输出:Window
3、自执行函数,同上面等价
自执行函数,同上面等价,this也是代指的window。
(function () {
console.log(this); // 输出:Window
})()
二、复合案例
1、类和函数结合案例
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变量,因此输出景女神。
2、让上例中自执行函数也打印对象的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(); // 文州 文州
3、自动实例化案例
obj = {
name: '文州',
age: 19,
getName:function () {
console.log(this.name); // 文州
var that = this;
(function () {
console.log(that.name); // 文州
})()
}
}
obj.getName();