iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 9
1
Modern Web

一步一腳印-紮紮實實學es6系列 第 9

ES6 中Class 私有方法與this的探討

在Object 中已經有內建許多的方法
來幫我助我們操作物件

https://ithelp.ithome.com.tw/upload/images/20181009/20110579VThY2RiNOe.png

在這邊筆記一下各種內建方法

  • Object.getOwnPropertyNames() 列出物件的屬性名稱
  • Object.Object.getPrototypeOf() 取得建構函式的prototype
  • Object.hasOwnProperty() 是否為Object 的私有屬性或方法

class 中的this 會指向實例

class Person{
    constructor(age,weight){
        this.age=age;
        this.weight=weight;
        
    }
    call_this(){
        return this;
    }
   

}
var Lolo=new Person(13,50)
// 看看這邊的`this` 指向誰
console.log(Lolo=== Lolo.call_this());

https://ithelp.ithome.com.tw/upload/images/20181009/20110579LUogNno0ou.png

static 定義 class 中的私有方法

剛才的例子中 call_this() 在Person 中是不能直接調用的
必需從 Person.prototype中才能調用
這算是與實例共用的方法

那怎麼定義私有方法呢? es6 中提供了一個關鍵字:static

class Person{
    constructor(age,weight){
        this.age=age;
        this.weight=weight;
        
    }
    call_this(){
        return this;
    }
    static SonCanNotUse(){
        console.log("老子專用");
        
    }

}
var Lolo=new Person(13,50)

Person.SonCanNotUse();
console.log("看看兒子能用嗎?")
Lolo.SonCanNotUse();

試試看大家就可以發現
瀏覽器跟我們說 SonCanNotUse 不是一個function !

https://ithelp.ithome.com.tw/upload/images/20181009/20110579SfLAaZ7rOJ.png

頗富好奇心的我們來扒開他們看看到底怎麼一回事

https://ithelp.ithome.com.tw/upload/images/20181009/20110579Ic8MqnUx9e.png

果然只有爸爸有

這就是老師父,總是要留壓箱寶,不傳弟子的
咦,那我們很好奇
既然是「私有」的方法
那兒子並不能呼叫
那在這邊用this 到底指向的是誰呢?
根據我們前面的推測…誰呼叫的就是誰的

所以只有爸爸能呼叫…那應該就是指向爸爸...?

讓我們來實驗看看,把剛剛的call_this()加上static

class Person{
    constructor(age,weight){
        this.age=age;
        this.weight=weight;
        
    }
    static call_this(){
        return this;
    }
    static SonCanNotUse(){
        console.log("老子專用");
		
        
    }
	

}
var Lolo=new Person(13,50)

Person.call_this()===Person

我們果然得到了ture!
https://ithelp.ithome.com.tw/upload/images/20181009/20110579CIGwMLO7LJ.png

不過雖然私有方法實例不能夠使用
但我們如果想繼承,行不行呢?
如果不能繼承那是不是很沒用阿
這樣要寫重覆的程式碼咧~

當然,事實就跟我們希望的一樣,如果是繼承的class 是可以使用被繼承class的私有方法的

下面先來小試身手

class Person{
    constructor(age,weight){
        this.age=age;
        this.weight=weight;
        
    }
    static call_this(){
        return this;
    }
    static SonCanNotUse(){
        console.log("老子專用");
		
        
    }
	

}

class SuperMan extends Person{
	constructor(age,weight,power){
		super();
		this.power=power;
		this.length=length;
	}
	hello(){
		console.log(`我是個有${this.power}戰鬥力的SuperMAN`);
	}
}
//繼承的SuperMan,可以使用被繼承的call_this()嗎?

我們明天再來好好談繼承

https://ithelp.ithome.com.tw/upload/images/20181009/20110579AYkrm2kJMT.png


上一篇
ES6中的Class,是什麼語法糖?
下一篇
ES6 的 Class 、super 的特例與繼承
系列文
一步一腳印-紮紮實實學es630
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言