JavaScript:原型链

  • 一切皆对象
  • 对象是由函数创建的
    原生构造函数:Array,String,Boolean,Number,RegExp,Function
let test = new Function("name","age","console.log(name,age)");
test('zzz',19);//zzz,19
  • 一个函数能充当两个作用,函数也是对象(能调用),也能new,同时函数含有构造函数的功能(类函数)
function User(){} 
let user = new User();
User.prototype.name='zzx'

class举例

class User2 {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  /**
   * 静态方法,可直接调用
   */
  static drink() {
    console.log("drinking")
  }

  /**
   * 动态方法,必须new实例调用,挂在prototype上
   */
  eat() {
    console.log("eating")
  }
}

let user = new User2('lucy','23');
user.eat();
User2.drink();

Arrray举例

// Arrray
let arr= [1,2,3,4]
console.log(arr.__proto__===Array.prototype) //true

//同理举例
let obj = {}
obj.__proto__===Object.prototype //true

// 函数举例
 function Fun(name,age){
    this.name=name;
    this.age=age;
    this.sayHi = function(){
      console.log(name,age)
    };
  }
let child = new Fun('lisa',18);  
child.__proto__===Fun.prototype //true

//加方法,通过prototype连接新方法,暴露给子用
  Fun.prototype.sayHello=function () {
    console.log(this.name,this.age,'sayHello')
  }
console.dir(Fun) // 

child.sayHi() //zzz 18
child.sayHello() //zzz 18 sayHello

  Fun.__proto__.sayGoodMorning=function () {
    console.log(this.name,this.age,'sayGoodMorning')
  }
child.sayGoodMorning(); // Error:child.sayGoodMorning is not a function

//正确调用方法
Fun.__proto__.sayGoodMorning.call(child); //zzz 18 sayGoodMorning
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值