面向对象:类的继承和原型链

面向对象:类的继承和原型链

Babel转码器:Es6 => Es5

polyfill

Babel 默认只转换新的 JavaScript 句法,全局对象的方法都不会转码。例如:Iterator、Generator、Set、Map、Proxy、Reflect、Symbol、Promise

 <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    class Person{
        constructor(name){
            this.name = name;
        }
        getName(){
            return this.name;
        }
    }
    let name1 = new Person('tom');
    console.log(name1.getName());
    console.log(name1.name);
    console.log(name1.getName() === name1.name);
    console.log(name1);
//     tom
// VM40:28 tom
// VM40:29 true
// VM40:30 Person {name: "tom"}

继承

使用super关键字继承父类变量

    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
    class Person{
        constructor(name){
            this.name = name;
        }
        getName(){
            return this.name;
        }
        changeName(){
            return this.name+window.location.href
        }
    }

    class PersonSon extends Person{
        constructor(name){
           super(name);
        }
        getName(){
            return this.name + " overWrite";
        }
    }
    let son = new PersonSon("name");
    console.log(son.getName());
    console.log(son.changeName());
    son.getName();

对象中this指向问题:apply、bind、call

通过自定义全局变量,在类中对变量进行赋值this,最后通过=== 判断this的指向;

另:== 和 === 不同

构造函数会开辟新的内存空间,造成内存浪费,使用prototype原型对象。
__proto__指向原型对象
就近原则

   function ren(name,age){
        this.name = name;
        this.age = age;
    }
    ren.prototype.getMsg = function(){
        return "原型链1";
    }
    ren.prototype.sex = "女";
    var objren = new ren('tom','18');
    console.log(objren);
    objren.sex = '男';
    console.log(objren.sex);
    console.log(objren.getMsg())
        // ren {name: "tom", age: "18"}
        // age: "18"
        // name: "tom"
        // sex: "男"
        // __proto__:
        // getMsg: ƒ ()
        // sex: "女"
        // constructor: ƒ ren(name, age)
        // __proto__: Object
        //男
        // VM46:17 原型链1

使用prototype定义方法

例如:

  Array.prototype.sums = function () {
            var sum = 0;
            for (var i = 1; i < this.length; i++) {
                sum += this[i];
            }
            return sum;
        }
        console.log(Array.prototype)
        let a = [1, 2, 3, 4, 5]
        console.log(a.sums());
区别
  • typeof classname === fun
  • {}.proto
  • function.prototype
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百度一下吧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值