ECMAScript 6知识点总结 --- 面向对象相关

  • 对象相关概念
    const str = new String('apple')
    
    // 判断实例在不在构造函数中:
    console.log(str instanceof String)
    // true
    
    // 从构造函数中获取原型:
    console.log(String.prototype)
    
    // 从实例中获取原型:
    // 先获取构造函数:
    console.log(str.constructor) // => String
    // 再从构造函数中获取原型:
    console.log(str.constractor.prototype)
    
    
    
    //浏览器的自带属性__proto__
    str.__proto__ = str.constractor.prototype = String.prototype
    
    String.__proto__ = Function.prototype
    // 解析:String是构造函数,其下也有__proto__属性,指向构造函数的构造函数的原型,因为构造函数也是函数,函数的构造函数是Function,所以...
    
    String.__proto__.__proto__ = Object.prototype
    // 解析:Function的__proto__指向Object,so...
  • ES5的面向对象

    function Person(name, age){
        this.name = name
        this.age = age
    }
    // 赋予构造函数两条属性
    
    Person.prototype.showname = function(){
        console.log(this.name)
    }
    // 赋予原型一个方法
    
    const person = new Person('cc', 18)
    person.showname()
    // cc
  • ES6的面向对象

    class Person{
        constructor(name, age){
            this.name = name
            this.age = age
        }
        showName(){
            console.log(this.name)
        }
    }
    const person = new Person('cc', 18)
    person.showName()
    // cc

    class是一个声明,与var let一样,作用是声明一个类

    class Div{        // 虽说是类,但是本质还是构造函数
        constructor(x, y){        // 构造函数
            this.x = x        // 共享属性,只在实例中生效
            this.y = y
        }
        move(){        // 共享方法,会自动放在prototype上
            console.log(666)
        }
    }
    const div = new Div(1, 2)
    
    
    console.log(Div)        // function
    
    console.log(Div.prototype.constructor === Div)        //true
    
    console.log(div.__proto__ === Div.prototype)        //true
    
    console.log(Object.getPrototypeOf(div) === Div.prototype)        //true
    // 实例身上的原型是指向构造函数的prototype
    
    console.log(div instanceof Div)        //true
    
    console.log(div.constructor)        //Div
    
    console.log(Object.getOwnPropertyNames(div))        //[x, y]
    // 查看实例身上自己的属性
    
    console.log(div.hasOwnProperty('x'))        //true
    //x属性为实例私有的
    
    console.log(div.hasOwnProperty('move'))        //false
    //move方法是在prototype上的,继承而来
    
    

猜你喜欢

转载自blog.csdn.net/qq_35415374/article/details/83306645
今日推荐