new在执行时会做四件事情
new会在内存中创建一个新的空对象
new 会让this指向这个新的对象
执行构造函数里面的代码 目的:给这个新对象加属性和方法
new会返回这个新对象 (所以构造函数里面不需要return)
this详解
JavaScript中的this指向问题,有时候会让人难以捉摸,随着学习的深入,我们可以逐渐了解
现在我们需要掌握函数内部的this几个特点
1. 函数在定义的时候this是不确定的,只有在调用的时候才可以确定
2. 一般函数直接执行,内部this指向全局window
3. 函数作为一个对象的方法,被该对象所调用,那么this指向的是该对象(谁调用指向谁)
4. 构造函数中的this指向对象的实例
// 1. 普通函数
function fn() {
console.log(this); // this 指向 window
}
fn();
// 2 对象方法
var obj = {
name: 'zs',
dance: function() {
console.log(this);
that = this;
}
}
obj.dance(); // this 指向 obj
console.log(that === obj); // true
// 3 构造函数
function Fn() {
this.age = '18';
console.log(this)
self = this;
}
var demo = new Fn(); // this 指向 demo
console.log(self === demo); // true