简体   繁体   English

如何创建一个将在JavaScript中返回自定义对象的方法

[英]How to create a method that will return a custom object in JavaScript

I want to create a method that will return an instance of a custom class in JavaScript. 我想创建一个方法,它将在JavaScript中返回自定义类的实例。

What I have: 我有的:

The model class: 模型类:

function ProductModel() {
    this.ProductName = "";
    this.ProductId = "";    
}

Method that should create and populate an object of the above class and return: 应该创建并填充上述类的对象并返回的方法:

function GetNewProductModel() {
    var newProduct = new ProductModel();

    newProduct.ProductName =  $("#textProductName").val();
    newProduct.ProductId = "";

    return newProduct;
}

The way it's called: 它的方式叫做:

function PreviewProduct() {
        var productModelForPreview = GetNewProductModel();
        console.log(productModelForPreview);
}

What I see: 我所看到的:

In the console I see this: 在控制台中我看到了这个:

function productModelForPreview()

What I can't seem to do: 我似乎无法做到的事情:

I expect to get a ProductModel whose properties can be accessed like any other object. 我希望得到一个ProductModel,其属性可以像任何其他对象一样被访问。

Surely I am missing the fundamentals here. 当然,我错过了这里的基本面。

Thanks in advance. 提前致谢。

There is no problem with your code. 您的代码没有问题。 I tested on Chrome (43), FF (31) and IE (9) and it just works as expected. 我测试了Chrome(43),FF(31)和IE(9),它只是按预期工作。 By the way I recommand you to 顺便提一句,我建议你

Your code is fine. 你的代码很好。 We can assume that you have exposed only the problematic part of it. 我们可以假设您只暴露了有问题的部分。 Though, nothing in that part of your code contains what make it fails. 但是,代码中那部分内容中没有任何内容包含使其失败的内容。 productModelForPreview is a function when you execute and it should be an object (an instance of ProductModel). productModelForPreview是一个执行时的函数,它应该是一个对象(ProductModel的一个实例)。

We can't help you but you can search in your code the assignment that makes productModelForPreview a function instead of an object. 我们无法帮助您,但您可以在代码中搜索使productModelForPreview成为函数而不是对象的赋值。

Your code is working perfectly fine. 你的代码工作得非常好。 Your observed behavior will happen if you write 如果你写的话会发生你观察到的行为

var productModelForPreview = GetNewProductModel;

but here it's fine. 但这里很好。

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

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