1. 程式人生 > >ECMAScript 6知識點總結 --- 面向物件相關

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上的,繼承而來