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

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

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

猜你喜欢

转载自blog.csdn.net/qq_45393395/article/details/120566966
今日推荐