this指向
this 指针允许快速访问当前上下文中的属性和方法
- 全局上下文中的
this: 当在全局作用域中调用普通函数时,this指向全局对象,通常是window对象(在浏览器环境中) 当我们用var来定义一个变量时,变量会绑定在全局对象上,自动成为全局对象的属性:
function Star() {
console.log(this.a) // 输出:'1'
}
var a = '1'
Star()
- 函数内部的
this: 当普通函数被作为方法调用时,this指向调用该函数的对象。
const obj = {
name: "John",
sayHello: function() {
console.log("Hello, " + this.name)
}
}
当然,直接使用 obj.name也能达到一样的效果。
const obj = {
name: "John",
sayHello: function() {
console.log("Hello, " + obj.name)
}
}
既然如此,为什么要使用this呢?个人观感,this在构造函数中才能发挥其真正作用。 this 让我们可以在构造函数内部动态地引用正在创建的对象的属性,而不需要知道对象的名称。
举个例子:
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log("Hello, " + this.name);
}
}
const person1 = new Person("John");
const person2 = new Person("Alice");
person1.sayHello(); // 输出 "Hello, John"
person2.sayHello(); // 输出 "Hello, Alice"
new
new的作用有三个:
- 开辟一块新的内存区域
- 让this指向新构建的对象
- 若构造函数有return值且return值为对象,返回return值,否则返回新构建的对象
手动实现一下:
const _new = function(Fn, ...args) {
// 补全代码
const obj = {}
const res = Fn.apply(obj, args)
obj.__proto__ = Fn.prototype
return typeof res === Object? res : obj
}
原型链
构造函数会有prototype属性,这个属性是一个对象,包含constructor属性(指回构造函数),和prototype属性。new出来的对象的对象原型__proto__会指向原型对象prototype。 如果没有prototype的话,每一次new就会开辟一块新内存存储相同的函数:
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log("Hello, " + this.name);
}
}
实现类继承:
首先这是父类:
function Star(name) {
this.name = name
}
Star.prototype.sing = function() {
console.log('let me sing')
}
这是子类:
function SuperStar(name, songs) {
Star.call(this, name)
this.songs = songs
}
SuperStar.prototype = Star.prototype
// 因为复制了Star的原型对象,所以constructor指向Star
console.log(SuperStar.prototype.constructor)
// 现在给它指回来
SuperStar.prototype.constructor = SuperStar