Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, April 8, 2022

JavaScript index




TypeError: 'undefined' Is Not a Function 解法










  使用 ~~ 比使用 Math.floor 的效能好













 
Table


Video/Audio






Wednesday, December 29, 2021

[JavaScript] preventDefault, stopPropagation

event.stopPropagation() 為了阻止事件繼續冒泡

event.preventDefault() 停止事件的默認動作

stopImmediatePropagation() 讓其他同一層級的 listener 也不要被執行

[JavaScript] input 停止輸入 key

 input 停止輸入 key

主要加上 evt.preventDefault()

=============================================

  checkSkipKey(evt) {

    let time = new Date().getTime()

    let key = evt.keyCode


    if((REPEAT_KEY_TIME > (time - this._timeStamp)) && (key == this._previousKey)) {

      this.log.show(this.debug_info,'skip key time - this._timeStamp:', time - this._timeStamp)

      return true

    }

    this._previousKey = key

    this._timeStamp = time

    return false

  }


    if(this.checkSkipKey(evt)) {

      if (!!evt) {

        evt.preventDefault()

        if(typeof evt.stopImmediatePropagation === 'function') {

          evt.stopImmediatePropagation()

        } else {

          evt.stopPropagation()

        }

      }

      return

    }

=============================================

Tuesday, October 26, 2021

[JavaScript] 深層複製

 https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Monday, October 11, 2021

[JavaScript] 分開兩個屬性選擇器

 input[class^='some_starting_constant_string'][class$='some_ending_constant_string']


 console.log( document.querySelectorAll("[class*='start'][class$='end']") ) 

 <div class="start__end"></div> <div class="start_heretoo_end"></div> <div class="sta__end"></div> <div class="rt__end"></div> <div class="start__d"></div> 

Wednesday, April 7, 2021

Saturday, December 12, 2020

this

this 所綁定的物件並非是函式宣告的時候所定義,而是在呼叫函式時的時機去決定 this 所指向的目標

四個規則如下

1. 預設繫結 -> 就是字面上的預設,若沒有其他三項規則下,通常 this 就是預設繫結也就是綁定到 global object,如上圖 first & second function 的 this 都屬於 global object

2. 隱含繫結 -> 當函式的呼叫是透過物件參考而呼叫的話,this 會被綁定到此物件上,而注意到的是假使是多個物件參考連結,是綁定於最後的物件,而注意到根據函式使用方式,有可能會丟失隱含繫結的綁定


3. 明確繫結 -> 不同於隱含系結須透過物件參考呼叫函式,所有的 JS 函式都可以透過 call(..) & apply(..) 來做 this 綁定


4. 硬繫結 -> 上述的系結方法都有可能遇到預料外的情況如 this 被某個 framework 給覆蓋掉,在 ES5 提供了 bind 來強制綁定,先前寫 react 的大家應該也很常使用到此方法


再來額外會影響到 this 繫結的還有透過 new 所創建出來的物件,以一個 new 的行為建立物件會有以下的行為

1. 建立一個全新的物件

2. 此物件會帶有 constructor function 的 prototype chain

3. 此物件會被設為 constructor function 中的 this

4. 除非函式自帶回傳物件,否則 new 會自動回傳新建的物件

而 this 綁定的優先順序則是從後到頭,也就是 new 物件繫結 > bind > call & apply > obj.function > default

總結

1. 是否為 new 所建立的物件,如果是則以 new 綁定的 this 為主

2. 透過 bind 硬繫結強制綁定函式與其對應的物件,注意到在 bind 參數裡面除了第一個為綁定的物件以外,後續的參數會被預設為綁定函式中的標準參數,技術上來說被稱為 currying

3. 透過 call & apply 明確指定函式運用的物件

4. 預設情況下的 this 為 global object 或者在嚴格模式執行下為 undefined

React 與 bind this 的一些心得

this





Wednesday, December 9, 2020

this 善用的方式

過去我們在寫物件內的函式時,為了確保 this 能夠正確運作會先將它賦予在另一個變數上 (that, self, vm…)。


箭頭函式本就會指向他所生成的物件上,所以可以不需要另外指向另一個物件。




綁定的 this 不同





綁定到其定義時所在的物件,我們要了解一般函式在建立時是在 window 下,所以在 window 下使

用箭頭函式自然會指向 window,要確實將箭頭函式宣告在物件內部,這樣 this 才會指向該物件。 



這個範例稍作複雜些,但只是要解釋不同建立方式的差異,注意:如果 不是 建立在物件內的函式,並不會影響箭頭函示的 this:

func() 是最外層的函式,他對於內層的箭頭不會有影響。
func2() 是包覆在內層的函式,但由於箭頭函式不是在物件內,所以沒有影響。
func3() 是呼叫在物件內的函式,因此箭頭函式會是使用它所在的物件。

縮寫的函式

另外注意:物件縮寫形式的函式也是屬於 function,所以依然能夠產生作用域。



Thursday, October 1, 2020

JavaScript question

1. What is the difference between undefined and not defined in JavaScript?

> var x; // declaring x

> console.log(x); //output: undefined 

=====================================================

> console.log(y);  // Output: ReferenceError: y is not defined

2. What will be the output of the code below?

var y = 1;

  if (function f(){}) {

    y += typeof f;

  }

  console.log(y);

The output would be 1undefined.

=====================================================

var k = 1;

  if (1) {

    eval(function foo(){});

    k += typeof foo;

  }

  console.log(k); 

The code above will also output 1undefined.

=====================================================

var k = 1;

  if (1) {

    function foo(){};

    k += typeof foo;

  }

  console.log(k); // output 1function

3.What is the drawback of creating true private methods in JavaScript?

One of the drawbacks of creating true private methods in JavaScript is that they are very memory-inefficient, as a new copy of the method would be created for each instance.

=====================================================

var Employee = function (name, company, salary) {

    this.name = name || "";       //Public attribute default value is null

    this.company = company || ""; //Public attribute default value is null

    this.salary = salary || 5000; //Public attribute default value is null


    // Private method

    var increaseSalary = function () {

        this.salary = this.salary + 1000;

    };


    // Public method

    this.dispalyIncreasedSalary = function() {

        increaseSlary();

        console.log(this.salary);

    };

};


// Create Employee class object

var emp1 = new Employee("John","Pluto",3000);

// Create Employee class object

var emp2 = new Employee("Merry","Pluto",2000);

// Create Employee class object

var emp3 = new Employee("Ren","Pluto",2500);

emp1.dispalyIncreasedSalary()

=====================================================

error: Uncaught ReferenceError: increaseSlary is not defined

=====================================================

Here each instance variable emp1, emp2, emp3 has its own copy of the increaseSalary private method.

So, as a recommendation, don’t use private methods unless it’s necessary.

4. What is a “closure” in JavaScript? Provide an example

A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in the parent function scope.

The closure has access to variables in three scopes:

Variables declared in their own scope

Variables declared in a parent function scope

Variables declared in the global namespace

=====================================================

var globalVar = "abc"; 


// Parent self invoking function 

(function outerFunction (outerArg) { // begin of scope outerFunction

    // Variable declared in outerFunction function scope 

    var outerFuncVar = 'x';    

    // Closure self-invoking function 

    (function innerFunction (innerArg) { // begin of scope innerFunction

        // variable declared in innerFunction function scope

        var innerFuncVar = "y"; 

        console.log(          

            "outerArg = " + outerArg + "\n" +

            "outerFuncVar = " + outerFuncVar + "\n" +

            "innerArg = " + innerArg + "\n" +

            "innerFuncVar = " + innerFuncVar + "\n" +

            "globalVar = " + globalVar);

 

    })(5)// end of scope innerFunction)(5); // Pass 5 as parameter 

})(7)// end of scope outerFunction )(7); // Pass 7 as parameter 

=====================================================

outerArg = 7

outerFuncVar = x

innerArg = 5

innerFuncVar = y

globalVar = abc

=====================================================

5. Write a mul function which will produce the following outputs when invoked:

=====================================================

function mul (x) {

    return function (y) { // anonymous function 

        return function (z) { // anonymous function

            console.log("x:"+x+",y:"+y+",z:"+z);

            return x * y * z; 

        };

    };

}

console.log(mul(2)(3)(4)); // output : 24 

console.log(mul(4)(3)(4)); // output : 48

=====================================================

x:2,y:3,z:4

24

x:4,y:3,z:4

48

=====================================================

6. How to empty an array in JavaScript?

var arrayList =  ['a','b','c','d','e','f'];

=====================================================

Method 1

var arrayList = ['a','b','c','d','e','f']; // Created array 

var anotherArrayList = arrayList;  // Referenced arrayList by another variable 

arrayList = []; // Empty the array 

console.log(anotherArrayList); // Output ['a','b','c','d','e','f']

Above code will set the variable arrayList to a new empty array. This is recommended if you don't have references to the original array arrayList anywhere else, because it will actually create a new, empty array. You should be careful with this method of emptying the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged.

=====================================================

Method 2

var arrayList = ['a','b','c','d','e','f']; // Created array 

var anotherArrayList = arrayList;  // Referenced arrayList by another variable 

arrayList.length = 0; // Empty the array by setting length to 0

console.log(anotherArrayList); // Output []

The code above will clear the existing array by setting its length to 0. This way of emptying the array also updates all the reference variables that point to the original array. Therefore, this method is useful when you want to update all reference variables pointing to arrayList.

=====================================================

Method 3

var arrayList = ['a','b','c','d','e','f']; // Created array 

var anotherArrayList = arrayList;  // Referenced arrayList by another variable 

arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0

console.log(anotherArrayList); // Output []

The implementation above will also work perfectly. This way of emptying the array will also update all the references to the original array.

=====================================================

Method 4

while(arrayList.length){

  arrayList.pop();

}

The implementation above can also empty arrays, but it is usually not recommended to use this method often.

=====================================================

7.How do you check if an object is an array or not?

The best way to find out whether or not an object is an instance of a particular class is to use the toString method from Object.prototype:

 var arrayList = [1,2,3];

Array.isArray(arrayList);

8.What will be the output of the following code?

=====================================================

var output = (function(x){

    delete x;

    return x;

  })(0);

  

  console.log(output);

The output would be 0. The delete operator is used to delete properties from an object. Here x is not an object but a local variable. delete operators don't affect local variables.


Reference:

https://www.codementor.io/@nihantanu/21-essential-javascript-tech-interview-practice-questions-answers-du107p62z


n8n index

 【n8n免費本地端部署】Windows版|程式安裝x指令大補帖  【一鍵安裝 n8n】圖文教學,獲得無限額度自動化工具&限時免費升級企業版功能