简体   繁体   English

在功能参数中强制对象结构

[英]Enforce object structure in function parameter

I am new to javascript. 我是javascript新手。 I have a function taking an object. 我有一个带对象的功能。 But how do I make sure caller is following the structure I want in the object. 但是,如何确保调用者遵循对象中所需的结构。 As there is no concept of class in javascript, I can't create a model class and make the caller use it ? 由于javascript中没有类的概念,因此我无法创建模型类并使调用者使用它?

function foo(myObject)
{

}

Whoever is calling should give me 谁打电话给我

{
  Count,
  [
    {
      FirstName,
      LastName
    },
    {
      FirstName,
      LastName
    },
  ]
}

Well you could simply check the type of object you have received as an argument, and then check if those values are actually there, like so: 好了,您可以简单地检查作为参数接收的对象的类型,然后检查这些值是否确实存在,如下所示:

function foo(myObject) {
    if (typeof myObject !== 'object') {
        // doesn't match
        return;
    }
    if (typeof myObject.Count === 'undefined') {
        // no count property
    }
}

However, from your question, it seems you would like to make it more fix which kind of object should be sent as an argument, and this you could also do in javascript, by doing for eg: 但是,从您的问题来看,您似乎想使其更固定应将哪种对象作为参数发送,并且您也可以在javascript中这样做,例如:

function MyParamOptions() {
    // define properties here
    this.persons = [];
    Object.defineProperty(this, 'Count', {
        get: function() {
            return this.Names.length;
        },
        set: function() {
            // dummy readonly
        }
    });
}

Then you could instantiate an instance of this class by saying 然后,您可以通过说出实例化此类的实例

var options = new MyParamOptions();
options.persons.push({ firstName: 'bla', lastName: 'bla' });

and change a check inside your foo function like 并在foo函数中更改检查,例如

function foo(myObject) {
    if (myObject instanceof MyParamOptions) {
        // here myObject is MyParamOptions, so you can access the persons array, the Count property etc...
    }
}

// and call foo with your MyParamOptions
foo(options);

However this will not throw any warnings at compile time, so people can call your function with any kind of parameter. 但是,这不会在编译时发出任何警告,因此人们可以使用任何类型的参数来调用您的函数。 If you are looking for errors at compile time, you might look into TypeScript or a similar technology that then transpiles your TypeScript code to javascript) 如果您在编译时寻找错误,则可以考虑使用TypeScript或类似的技术,然后将您的TypeScript代码转换为javascript)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM