2020年1月2日 星期四

javascript

javascript

javascript notes

var that = this

如果在object中執行ajax,想在.done(或success)中設定好Object的property,那可能會需要使用此技巧。

例:

class testObj{
    constructor(){
        var that = this
        $.ajax({
    	    url: "someurl...",
	    type: "GET",
	    contentType: "json"
        }).done(function(data){
	    console.log(data)
	    that.hostname = data.info.hostname
        })
    }
};
a = new testObj()
console.log(a.hostname)

看起來感覺很糟,除此之外尚有另外的解法:


class testObj{
    constructor(){
        $.ajax({
    	    url: "someurl...",
	    type: "GET",
	    contentType: "json",
	    context: this
        }).done(function(data){
	    console.log(data)
	    this.hostname = data.info.hostname
        })
    }
};
a = new testObj()
console.log(a.hostname)

嗯…還是醜醜的
javascript要寫得好看不容易呀

解構子

可以拿來組合兩個array

example

a = [1, 2, 3]
b = [4, 5, 6]
console.log([...a, ...b])
//except: [1, 2, 3, 4, 5, 6]

沒有留言:

張貼留言