professor_robot
professor_robot

Reputation: 41

assign value to function object

I have a object called DummyObject with a property called 'value' I am trying to assign a value through the function 'assignValue' but it shows up undefined after I try to assign it. I am assuming that in the 'assignValue' function the 'v' should be pointing to 'this.value' and when i assign it to that it should update 'this.value'.

function DummyObject(){
    this.value;
}

DummyObject.prototype.assignValue = function(val){
    var v = this.value;
    v = {val: val};
}

var dObj = new DummyObject();
dObj.assignValue(23);

console.log(dObj);

Upvotes: 0

Views: 74

Answers (4)

Miguel
Miguel

Reputation: 20633

References are kept for objects but this.value is undefined (non-object) so it won't work as you're thinking it would. Initialize it with an object and that will work by modifying the specific property.

function DummyObject() {
    this.value = {};
}

DummyObject.prototype.assignValue = function(val) {
    var v = this.value;
    v.val = val;
}

var dObj = new DummyObject();
dObj.assignValue(23);

console.log(dObj); // {value: {value: 23}}

However, the best way would be to modify this.value directly.

this.value = {val: val};

Upvotes: 2

wolfhammer
wolfhammer

Reputation: 2661

Take a look at prototype.toString for making a custom object value. I think there might be issues with it since I don't see it used very often. You may want to use dObj.value to avoid any problems.

function DummyObject(){
    this.value;
}

DummyObject.prototype.assignValue = function(val){
    this.value = val;
};

DummyObject.prototype.toString = function() {
    return this.value;
};

var dObj = new DummyObject();
dObj.assignValue(23);

var out = document.getElementById('out');

out.innerHTML += dObj;
<pre id="out"></pre>

Upvotes: 0

Dan Crews
Dan Crews

Reputation: 3637

JS doesn't reserve your pointer if you ever say:

thing = newThing

Your local variable v is no longer pointing at this.value, so just drop that variable altogether. If you want to set a bunch of things, you can use an object, which is passed by reference:

function DummyObject() {
  this.value;
}

DummyObject.prototype.assignValue = function(val) {
  var v = this.value = { val: val };
  v.somethingElse = 'someData';
}

Upvotes: 0

Pointy
Pointy

Reputation: 413996

Variables in JavaScript don't work that way. When you create the variable v with

var v = this.value;

you create something that's completely independent from this.value, not an alias to this.value. If you want to change this.value you have to do so directly.

this.value = {val: val};

Upvotes: 1

Related Questions