js (this,原型与闭包)

this

  • 有对象指向对象;
  • 没对象指向全局变量(window);
  • 有new指向new出的新对象;
  • bind,call&apply改变this的指向;
  • setTimeout/setInterval this指向window;
  • 箭头函数 this 是由函数定义时候确定的

var adder = {
  base : 1,
    
  add : function(a) {
    var f = v => v + this.base;
    return f(a);
  },

  addThruCall: function inFun(a) {
    var f = v => v + this.base;
    var b = {
      base : 2
    };
            
    return f.call(b, a);
  }
};

console.log(adder.add(1));

var obj = {
  i: 10,
  b: () => console.log(this.i, this),
  c: function() {
    console.log( this.i, this)
  }
}
obj.b();  // undefined window{...}原型
obj.c();  // 10 Object {...}

原型

prototype:

  • prototype:每一个对象都会在其内部初始化一个属性:即prototype;
  • 原型链:当我们访问一个对象的属性时,如果这个对象内部不存在这个属性,那么就回去__proto__里找这个属性,这样一直找下去就是:原型链;
  • instanceof 原理是判断实例对象的__proto__和生成该实例的构造函数的prototype是不是引用的同一个地址。
  • hasOwnProperty 是 JavaScript 中唯一一个处理属性但是查找原型链的函数。

构造函数  ->prototype-> 原型对象 -> constructor -> 构造函数

构造函数 -> new -> 实例对象

实例对象 -> __proto__-> 原型对象-> __proto__->原型对象->->null

 

执行上下文:

变量声明与函数声明,其作用域会提升到方法体的顶部;

作用域:

  • javascript没有块级作用域
  • javascript除了全局作用域之外,只有函数可以创建的作用域。作用域在函数定义时就已经确定了。而不是在函数调用时确定。

闭包:

  • 概念: 内部函数可以访问外部函数中的变量;
  • 使用:函数作为返回值;函数作为参数;
  • 作用:封装变量,收敛权限;
  • 缺点:消耗内存

创建对象的方法:

  • 对象字面量;
  • 构造函数;
  • 立即执行函数;
  • Object.create();

new 对象过程:

  • 创建新对象;
  • this指向这个新对象;
  • 执行代码;
  • 返回this;

类与继承:

类的声明:

function Animal(){
    this.name = 'name';
}

// es6 

class Animal2{
    constructor(){
        this.name = 'name2';
    }
}

继承:

1.借助构造函数实现继承

function Parent(){
    this.name = 'parent';
}

function Child(){
    Parent.call(this);
    this.type = 'child1';
}

缺点:部分继承;继承不到父类原型对象上的方法;(只有父类的属性挂载到子类上了,Child的prototype没变为Child.prototype继承不了Parent的prototype)

2.原型链继

function Parent(){
    this.name = 'name';
}
function Child(){
    this.type = 'child';
}

Child.prototype = new Parent();

缺点:原型链上原型对象是共用的。(原型的属性修改,所有继承自该原型的类的属性都会一起改变)

3.组合方式

function Parent(){
    this.name = 'parent';
}
function Child(){
    Parent.call(this);
    this.type = 'child';
}
Child.prototype = new Parent();

缺点:父类执行函数执行两次;constructor指向父类;

function Parent(){
    this.name = 'parent';
}
function Child(){
    Parent.call(this);
    this.type = 'child';
}
Child.prototype = Parent.prototype;

缺点:子类constructor指向父类

function Parent(){
    this.name = 'parent';
}
function Child(){
    Parent.call(this);
    this.type = 'child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

优点:子类的原型指向Object.create(Parent.prototype),实现了子类和父类构造函数的分离,但是这时子类中还是没有自己的构造函数,所以紧接着又设置了子类的构造函数,由此实现了完美的组合继承。(也就是把父类的prototype写入子类的prototype,在定义子类的constructor)

4. es6

class Child extends Parent {
    constructor(){

    }
}

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值