禁用函数

时间:2018-05-12 14:15:29

标签: 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

问题是,Z.ABC不是函数Shape和Rectangle下的变量,它应该会出现错误,因为ABC不是形状和矩形函数下的变量。

如何禁用未知变量,不允许在函数外声明未知变量?

2 个答案:

答案 0 :(得分:5)

在构建对象并添加所需的所有属性后,可以在对象上调用Object.preventExtensions。您当时无法在对象上创建新属性。

"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

答案 1 :(得分:1)

为了防止对象的分配操作,你可以"冻结"他们。 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);