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

Monday 19 June 2023

What actually bind in Javascript

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// Expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// Expected output: 42

The output :

> undefined > 42



Source :  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Friday 16 June 2023

What is the super() keyword or function in JavaScript

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.


The concept of super keyword comes with the idea of inheritance in JavaScript. Suppose that you have a member variable or method of the same name in the derived class as you do in the base class.

When referring to that variable/method, how would the program know if you are referring to the base class or the derived class?


This is where super comes into play. The super keyword in JavaScript acts as a reference variable to the parent class.

It is mainly used when we want to access a variable, method, or constructor in the base class from the derived class.

Let’s have a look at some examples to understand exactly how the super keyword works.


Example Scripts

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Class Inheritance</h2>

<p>Use the "extends" keyword to inherit all methods from another class.</p>
<p>Use the "super" method to call the parent's constructor function.</p>

<p id="demo"></p>

<script>
class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I have a ' + this.carname;
  }
}

class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}

mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();
</script>



</body>
</html>


Output :




Calling super in static methods
super can also be used to call on static methods of the parent class:

<script>
    class Rectangle {
      constructor() {}
      static getDescription() {
        return 'I have 4 sides';
      }
    }
   
    class Square extends Rectangle {
      constructor() {
        super()
      }
      static getDescription() {
        return super.getDescription() + ' which are all equal';
      }
    }
    console.log(Square.getDescription())
 </script>


The output :

I have 4 sides which are all equal




Source : https://www.w3schools.com/jsref/jsref_class_super.asp
https://www.educative.io/answers/what-is-the-super-keyword-in-javascript

Tuesday 6 June 2023

What is preventDefault() Even Method

Event: preventDefault() method

The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

As noted below, calling preventDefault() for a non-cancelable event, such as one dispatched via EventTarget.dispatchEvent(), without specifying cancelable: true has no effect.

Syntax

event.preventDefault()

Examples

Blocking default click handling

Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that from happening:

JavaScript

const checkbox = document.querySelector("#id-checkbox");

checkbox.addEventListener("click", checkboxClick, false);

function checkboxClick(event) {
  let warn = "preventDefault() won't let you check this!<br>";
  document.getElementById("output-box").innerHTML += warn;
  event.preventDefault();
}

HTML

<p>Please click on the checkbox control.</p>

<form>
  <label for="id-checkbox">Checkbox:</label>
  <input type="checkbox" id="id-checkbox" />
</form>

<div id="output-box"></div>

Result

Stopping keystrokes from reaching an edit field

The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault(). Nowadays, you should usually use native HTML form validation instead.

HTML

The HTML form below captures user input. Since we're only interested in keystrokes, we're disabling autocomplete to prevent the browser from filling in the input field with cached values.

<div class="container">
  <p>Please enter your name using lowercase letters only.</p>

  <form>
    <input type="text" id="my-textbox" autocomplete="off" />
  </form>
</div>

CSS

We use a little bit of CSS for the warning box we'll draw when the user presses an invalid key:

.warning {
  border: 2px solid #f39389;
  border-radius: 2px;
  padding: 10px;
  position: absolute;
  background-color: #fbd8d4;
  color: #3b3c40;
}

JavaScript

And here's the JavaScript code that does the job. First, listen for keypress events:

const myTextbox = document.getElementById("my-textbox");
myTextbox.addEventListener("keypress", checkName, false);

The checkName() function, which looks at the pressed key and decides whether to allow it:

function checkName(evt) {
  const charCode = evt.charCode;
  if (charCode !== 0) {
    if (charCode < 97 || charCode > 122) {
      evt.preventDefault();
      displayWarning(
        "Please use lowercase letters only.\n" + `charCode: ${charCode}\n`
      );
    }
  }
}

The displayWarning() function presents a notification of a problem. It's not an elegant function but does the job for the purposes of this example:

let warningTimeout;
const warningBox = document.createElement("div");
warningBox.className = "warning";

function displayWarning(msg) {
  warningBox.innerHTML = msg;

  if (document.body.contains(warningBox)) {
    clearTimeout(warningTimeout);
  } else {
    // insert warningBox after myTextbox
    myTextbox.parentNode.insertBefore(warningBox, myTextbox.nextSibling);
  }

  warningTimeout = setTimeout(() => {
    warningBox.parentNode.removeChild(warningBox);
    warningTimeout = -1;
  }, 2000);
}

Result

Notes

Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect. 







Source : https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault