Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable unknown variable in function [duplicate]

Tags:

javascript

function Shape(X,Y) {
    this.X = X;
    this.Y= Y;
}

function Rectangle(Name,Desc,X,Y) {
    Shape.call(this, X, Y);
    this.Name = Name;
    this.Desc = Desc;
}

var Z = new Rectangle('Rectangle', '',25,25);
Z.ABC = '123';

enter image description here

The problem is, the Z.ABC is not the variable under the function Shape and Rectangle, it should hit error because ABC is not the variable under shape and rectangle function.

How to disable unknown variable, not allow to declare unknown variable outside the function ?

like image 869
Howard Teoh Avatar asked May 12 '18 14:05

Howard Teoh


2 Answers

You can call Object.preventExtensions on your object after constructing it and adding all the properties that you want. You won't be able to create new properties on the object then.

"use strict";
function Shape(X,Y) {
    this.X = X;
    this.Y= Y;
}

function Rectangle(Name,Desc,X,Y) {
    Shape.call(this, X, Y);
    this.Name = Name;
    this.Desc = Desc;
}

var Z = Object.preventExtensions(new Rectangle('Rectangle', '',25,25));
Z.ABC = '123'; // Uncaught TypeError: Cannot add property ABC, object is not extensible
like image 75
Bergi Avatar answered Oct 12 '22 17:10

Bergi


To prevent assignment operations to your objects you can "freeze" them. Reference

function Shape(X,Y) {
    this.X = X;
    this.Y= Y;
}

function Rectangle(Name,Desc,X,Y) {
    Shape.call(this, X, Y);
    this.Name = Name;
    this.Desc = Desc;
}

var Z = new Rectangle('Rectangle', '',25,25);
Object.freeze(Z);
Z.ABC = '123';
console.log(Z);
like image 43
Randy Casburn Avatar answered Oct 12 '22 17:10

Randy Casburn