Javascript中的this和继承

274 阅读2分钟

this指向

this在浏览器中的指向

1.this总是指向调用它所在方法的对象
this的指向与所在方法的调用位置有关,而与方法的声明位置无关

2.在浏览器中,调用方法时没有明确对象的,this 指向window

3.在浏览器中setTimeout、setInterval和匿名函数执行时的当前对象是全局对象window

apply 和 call

apply和call能够强制改变函数执行时的当前对象,让this指向其他对象 apply,call没有明确对象的(传空,undefined,null),this指向window

bind

bind可以实现函数柯里化
test.bind(xxx)//不会立即执行
test.call(xxx)//会立即执行

nodejs中this指向

In Node.js this is different. The top-level scope is not the global scope; var something inside a Node.js module will be local to that module.//this 指向模块,如果没有定义模块则指向global
但是在Node CLI(node命令行)下,与浏览器的行为保持一致

eval和call,apply

eval等同于在声明位置填入代码
evla也可以用call和apply

es6中的this

因为js的this太古怪,所以ES6开始,箭头函数,是在声明时候绑定this的
但是在use strict模式下,this的绑定规则有点不一样:developer.mozilla.org/zh-CN/docs/…
一个开启严格模式的函数,指定的this不再被封装为对象,而且如果没有指定this的话它值是undefined

Javascript 继承

面向对象 我们知道OOP(面向对象)的三的特性是:封装、继承、多态:
凡是不希望别人知道内部实现的则进行封装,内外隔离
凡是系统需要归一化,为了处理方便对所处理的对象有统一要求,则使用继承和多态

ES6继承

1.Class通过extends关键字实现继承
2.子类必须在constructor方法中调用super方法,否则新建实例时会报错

ES5继承

原型链继承
// 假设有一个需要继承的一个类型 Animal

function Cat() {}
Cat.prototype = new Animal()
// 添加一个属性
Cat.prototype.name = 'cat'
构造继承
// 假设有一个需要继承的一个类型 Animal

function Cat(name){
  Animal.call(this)
  // 添加一个属性
  this.name = name || 'cat'
}
所以组合这两个东东:组合继承
// 假设有一个需要继承的一个类型 Animal

function Cat(name) {
  Animal.call(this)
  // 添加属性
  this.name = name || 'cat'
}
Cat.prototype = new Animal()
// 添加方法
Cat.prototype.say = function () {
  // TOOD
}
优化内存节省一些:
// 假设有一个需要继承的一个类型 Animal

function Cat(){
  Animal.call(this)
  this.name = 'cat'
}

(function(){
  // 创建一个没有实例方法的类
  var Super = function () {}
  Super.prototype = Animal.prototype
  // 将实例作为子类的原型
  Cat.prototype = new Super()
  // 添加方法
  Cat.prototype.say = function () {
    // TOOD
  }
})()