Scoped safety of high-level functions of the constructor

Constructors know. Is a function call using the new operator. When a new call, this object is used in the constructor points to the newly created object instance.

function Person(name,age,job) {
    this.name = name;
    this.age = age;
    this.job = job;
}
let person = new Person('yk',27,'software Engineer')

The above example, Person this object constructor is used to assign three properties, name, age and job. When there is no new problem, when called directly, this is mapped to the global window above. Create a scoped safety constructor can solve this problem.

function Person(name,age,job) {
    if(this instanceof Person) {
            this.name = name;
            this.age = age;
            this.job = job;
    } else {
        return new Person(name,age,job)
    }
}

eg2:

function Polygon(sides) {
    if(this instanceof Polygon) {
        this.sides = sides;
        this.getArea = function() {
            return 0; } } else { return new Polygon(sides) } } function Rectangle(width,height) { Polygon.call(this, 2); this.width = width; this.height = height; this.getArea = function() { return this.width * this.height; } } let rect = new Rectangle(5, 10); alert(rect.sides) //undefined 

As the scope Polygon constructor is safe, this is not the object Polygon instance, it will create and return a new Polygon object, this Rectangle object constructor has not been growing. Meanwhile Polygon.call value returned () to useless, so that there will be instances sides Rectangle properties.

function Polygon(sides) {
    if(this instanceof Polygon) {
        this.sides = sides;
        this.getArea = function() {
            return 0; } } else { return new Polygon(sides) } } function Rectangle(width,height) { Polygon.call(this, 2); this.width = width; this.height = height; this.getArea = function() { return this.width * this.height; } } Rectangle.prototype = new Polygon(); let rect = new Rectangle(5, 10); alert(rect.sides) //2 

Scan code plus group, daily updates an article front-end technology to grow together.

 

Guess you like

Origin www.cnblogs.com/bbqq1314/p/12545478.html