Tuesday, December 27, 2022

NewTarget and new.target

NewTarget

example 01


base_obj = {
    "constructor" : my_constructor,
}

function my_constr_stub()
{
    console.log("in constructor stub:new.target=" + new.target);//undefined
}

function my_constructor()
{
    console.log("in constructor:new.target=" + new.target);// function my_constructor(){...
    my_constr_stub();
}

my_constructor.prototype = base_obj;

new my_constructor()

Object [[Construct]](a List of any, newTarget)

The second argument is the object to which the new operator was initially applied. For example, in following code, the new operator is initially applied to the Square object:

class Rectangle {
  constructor(height, width) {
    console.log("in Rectangle:new.target=" + new.target);
    this.name = 'Rectangle';
    this.height = height;
    this.width = width;
  }
}

class Square extends Rectangle {
  constructor(length) {
    console.log("in Square:new.target=" + new.target);
    super(length, length);

    this.name = 'Square';
  }
}

aS = new Square(2);
console.log(
    "name=" + aS.name +
    ";height=" + aS.height
);

No comments:

Post a Comment