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.

What do I have:

Model class:

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

      

A method that should create and fill an object of the above class and return:

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

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

    return newProduct;
}

      

What is it called:

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

      

What do I see:

In the console, I see the following:

function productModelForPreview()

      

What I cannot do:

I expect to get a ProductModel whose properties can be accessed like any other object.

Of course I am missing a reason here.

Thanks in advance.

+3


source to share


3 answers


You have no problem with your code. I tested Chrome (43), FF (31) and IE (9) and it works fine. By the way, I recommend you



0


source


Your code is fine. We can assume that you only encountered the problematic part of it. Although, nothing in this part of your code contains what makes it fail. productModelForPreview

is a function at runtime and must be an object (a ProductModel instance).



We can't help you, but you can search your code for an assignment that makes a productModelForPreview

function instead of an object.

0


source


Your code works fine. Your observable behavior will happen if you write

var productModelForPreview = GetNewProductModel;

      

but that's ok here.

0


source







All Articles