Mike
Mike

Reputation: 27

JavaScript - Instantiate a object and assign it to another existing variable?

Been trying to instantiate an object (called "isSize" below) and assign it to another existing variable (called "sizeObject"), here is the first object ("isSize") within a function:

function Size(isSize) {
this.isSize = 80;
setSize(this.isSize);
}

And here's the second variable of which I want to assign the previous variable to:

var sizeObject;

I've been trying various ways such as the following:

function createSize(isSize){
var isSize = new sizeObject();
}

Anyone got any ideas? Many thanks

Upvotes: 0

Views: 248

Answers (2)

Mouad Debbar
Mouad Debbar

Reputation: 3226

If I understand your comment correctly, here is what you are looking for:

// this is the constructor of the `Size` class
function Size() {
  this.isSize = 80;
}

function createSize() {
  // add this line:
  var sizeObject = new Size();
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074949

It's very hard to understand quite what you're asking, but this:

var sizeObject = new Size(20);

...will create a new object with a isSize property on it with the value 20 if you change Size to:

function Size(initialSize) {
    this.isSize = initialSize;
}

(E.g., so it actually uses the argument you give it, rather than using an hardcoded 80.)

Size in the above is a constructor function. You use constructor functions via new.

Upvotes: 0

Related Questions