iT邦幫忙

0

js static 一問(2)

  • 分享至 

  • xImage

請問一下為何在constructor 裡initiate 了this.type , 但在
typeAppendCell call THIS.getType() 之後 THIS.type 是undefined.....
剛才找到是因為在constructor 裡init, 所以要在class 外面create chartAction 的object, 但這樣到處都是不同的object,
var caobj1 = new ChartAction();
caobj1.typeAppendCell()
var caobj2 = new ChartAction();
caobj2.typeAppendCell()
var caobj3 = new ChartAction();
caobj3.typeAppendCell()

這樣的另外一個寫法大家覺得怎樣
console.log((new chartAction()).type);

有沒有更好的寫法.謝謝

class chartAction {

    constructor() {

		this.type = ['rf3', 'spd', 'dir', 'tc2', 'td2', 'rh2', 'slp', 'hcld', 'mcld', 'lcld', 'ki', 'cape', 'lgt', 'srh', 'dp972', 'dps'];
	}
	
	static getType() {
        return this.type; 
    }

    static typeAppendCell(cellType="") {
        let THIS = this
        var idtype = "";

        console.log(THIS.getType())
        
        if(cellType != "") {
            console.log(cellType)
            idtype = cellType;
        } else {
            console.log(THIS.type)
            idtype = THIS.type;
        }

        for ( var t = 0; t < idtype.length; t++){
            if ( false ) {

                THIS.svgheight = THIS.svgheight_small;
            } else {
                THIS.svgheight = THIS.svgheight_large;
            }
            d3.select("#div_" + idtype[t]).append("div")
                .attr("class", idtype[t] + " ccell")
                .attr("id", idtype[t])
                .attr("width", THIS.svgwidth)
                .attr("height", THIS.svgheight)
                .attr("display", "inline-table")

            //console.log(THIS.type[t])
            d3.select('#' + idtype[t])
                .append("svg")
                .attr("width", THIS.svgwidth)
                .attr("height", THIS.svgheight)
                .attr("class", "psvg div_cell_wrap")
                .attr("id", "psvg" + t)

            ccobj.addCloseBtn(idtype[t])

            ccobj.addMinimizeBtn(idtype[t])

        }
    }
	
}
看更多先前的討論...收起先前的討論...
fillano iT邦超人 1 級 ‧ 2021-12-01 11:00:23 檢舉
為什麼要用static?你提的case都是不需要static的。
diu7me iT邦新手 4 級 ‧ 2021-12-01 11:05:15 檢舉
因為我想在class 外面不用再create object 來call, 直接class.method
fillano iT邦超人 1 級 ‧ 2021-12-01 11:05:34 檢舉
另外,你要把定義跟執行分開,class定義時,this指向class,但是執行時,constructor裡面的this指向instance,而其他static方法裡面的this指向class。
fillano iT邦超人 1 級 ‧ 2021-12-01 11:07:27 檢舉
這樣幹嘛定義class...static不是為了你不想create object而設計的。

另外,constructor是在create object時才執行,所以你要怎樣不create object?
diu7me iT邦新手 4 級 ‧ 2021-12-01 11:13:40 檢舉
只是想在class 外面 用chartAction.method, chartAction.attribute, 和在class 的static method 裡可以call 本class 的attribute 和method,

因為現在在class 外面call chartAction.method(), 裡面用this.type就不行,
我本意只是到處方便只用class就能call, 不用到處init 更多的object會做成混亂
diu7me iT邦新手 4 級 ‧ 2021-12-01 11:30:10 檢舉
開始的時候我打算在class attribute 用static, 因為全都是class裡面用的,

class chartAction {
static def_station =
[
'[30 HK Grids] ',
'[WGL] ',
'[WGL] ',
'[SE] ',
'[SE] ',
'[SE] ',
'[SE] ',
'[30 HK Grids] ',
'[30 HK Grids] ',
'[30 HK Grids] ',
'[30 HK Grids] ',
'[30 HK Grids] ',
'[Sum of 30 HK Grids] ',
'[30 HK Grids] ',
'',
''
];
static station = def_station;
}

但這樣就出了error,
chartAction.js:170 Uncaught ReferenceError: def_station is not defined
at Function.<static_initializer> (chartAction.js:170)
at chartAction.js:1
fillano iT邦超人 1 級 ‧ 2021-12-01 11:50:23 檢舉
this在javascript是最基本但是很容易弄錯的概念,因為他是執行時根據上下文動態決定的,所以先把他弄清楚。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
fillano
iT邦超人 1 級 ‧ 2021-12-01 11:33:42
最佳解答

我本意只是到處方便只用class就能call, 不用到處init 更多的object會做成混亂

這樣的話,與其用class + status,不如直接用object來匯集方法。像這樣

const Utils = {
    config: {},
    setConfig: function(config) {
        this.config = config;
    },
    tool1: function(param) {
        if(config.set1) return param;
        return false;
    }
}
Utils.tool1('done');

另外,其實可以用module來整理程式架構,並不是一定需要class的。而且class其實只是一個語法糖/images/emoticon/emoticon37.gif。javascript的class是協助你寫程式用的,底層還是原本的prototype based inheritance的東西。

1
海綿寶寶
iT邦大神 1 級 ‧ 2021-12-01 11:28:37

如果這是你要的
就參考拿去改

重點:不用 new object,連一次都不用

資料來源

class Triple {
  static triple(n) {
    n = n || 1; //should not be a bitwise operation
    return n * 3;
  }
}

class BiggerTriple extends Triple {
  static triple(n) {
    return super.triple(n) * super.triple(n);
  }
}

console.log(Triple.triple());        // 3
console.log(Triple.triple(6));       // 18
console.log(BiggerTriple.triple(3)); // 81
var tp = new Triple();
console.log(tp.triple());             // 'tp.triple is not a function'.

之前的問題如果解決了的話
就選個最佳解答

看更多先前的回應...收起先前的回應...
diu7me iT邦新手 4 級 ‧ 2021-12-01 11:31:15 檢舉

開始的時候我打算在class attribute 用static, 因為全都是class裡面用的,

class chartAction {
static def_station =
[
'[30 HK Grids] ',
'[WGL] ',
'[WGL] ',
'[SE] ',
'[SE] ',
'[SE] ',
'[SE] ',
'[30 HK Grids] ',
'[30 HK Grids] ',
'[30 HK Grids] ',
'[30 HK Grids] ',
'[30 HK Grids] ',
'[Sum of 30 HK Grids] ',
'[30 HK Grids] ',
'',
''
];
static station = def_station;
}

但這樣就出了error,
chartAction.js:170 Uncaught ReferenceError: def_station is not defined
at Function.<static_initializer> (chartAction.js:170)
at chartAction.js:1

diu7me iT邦新手 4 級 ‧ 2021-12-01 11:31:49 檢舉

到底要怎樣才可以assign 一個static attribute 到另外一個... 謝謝

diu7me 大大看一下我已經回答你了

fillano iT邦超人 1 級 ‧ 2021-12-01 11:45:06 檢舉

class跟他的instance是不一樣物件,static方法中的this會指到class而不是他的instance。constructor是在產生instance時執行,裡面的this會指到instance,在裡面要操作static屬性,要透過class。

前面加上 chartAction
static station = chartAction.def_station;

https://ithelp.ithome.com.tw/upload/images/20211201/20001787Riq6AGMdo3.png

fillano iT邦超人 1 級 ‧ 2021-12-01 11:48:04 檢舉

javascript的this是執行時動態決定的,你要看上下文才知道this是啥。

diu7me iT邦新手 4 級 ‧ 2021-12-01 11:55:42 檢舉

謝謝3位

我要發表回答

立即登入回答