Create an instance of object internally

48 views Asked by At

I have tried to create an instance of object internally like the following:

var oo = function(){
    return new func();
}

var func = function(){
    this.name;
    this.age;  
};

func.prototype = {
    setData: function(name, age){
        this.name = name;
        this.age = age;
    },
    getData: function (){
        return this.name + " " + this.age;
    }
}

When usage, I got an error oo.setData is not a function.

oo.setData("jack", 15);
console.log(oo.getData());

What's wrong in my code?

2

There are 2 answers

2
userbd On BEST ANSWER

This happens because oo is not a "func", oo returns a new func. You could set the data using

oo().setData('jack',15);

But then you have no way of accessing it.

You could also use

var newfunc = oo();
newfunc.setData('jack',15);
newfunc.getData();
0
Walter Chapilliquen - wZVanG On

oo is a function to create a object.

var oo = function(){ //the oo variable is used to create func() objects
    return new func();
}

var func = function(){ //function
    this.name;
    this.age;  
};

func.prototype = { //define properties to func
    setData: function(name, age){
        this.name = name;
        this.age = age;
    },
    getData: function (){
        return this.name + " " + this.age;
    }
}

//create instance
var myObject = oo();
//or
var myObject = new func();

//Use
myObject.setData("jack", 12);

//Get a property
console.log(myObject.getData())