Hi I'm trying to implement a LinkedList in Javascript. When i assign a value to my node it doesn't seem to store it when I use my getter. For example:
var Node =function() {
var _data;
var _next ={};
var that = this;
that.getData = function() {
return _data;
};
that.setData = function(data) {
that._data = data;
};
that.getNext = function() {
return _next;
};
that.setNext = function(next) {
that._next = next;
};
return that;
};
Will not work with:
var nodeObj = new Node();
nodeObj.setData("hello");
console.log(nodeObj.getData());
_data is not the same as that._data, you must do this:
that.getData = function() {
return that._data;
};
OR you could do this instead:
that.setData = function(data) {
_data = data;
};
the benefit of the second approach being that you're simulating a private variable (because you cannot do nodeObj._data in the second case but you can in the first)
also var that = this; is unnecessary, you can simply do this._data in this case.
For your case here, you can assume that if you're calling a function like yourObject.someFunction(), then within someFunction the value of this equals yourObject. (And this isn't always true in javascript but since you're starting off you should think about it this way for now. If you pass a function to another function as a variable and then call it then this wouldn't be the case).
Related
Facing inheritance problem in this below code i am new to OOPS concepts please help me.
var testA = function() {
this._data = undefined
};
testA.prototype.init = function(data) {
this._data = data;
};
testA.prototype.get = function(data) {
if (this._data) {
return data
}
};
var testB = function() {}
testB.prototype = Object.create(testA);
var instance = new testB();
testB.prototype.init = function(data) {
testA.prototype.init.call(this, data);
};
testB.prototype.Somedata = function() {
testA.prototype.get();
}
instance.init("testdata");
instance.Somedata() // here i am getting this._data is undefined
When i call instance.init("testdata") now it's setting value to this._data in the parent.
When i call instance.Somedata() here i am getting undefined
May i know what could be reason? and how can i get the this._data value when i call instance.Somedata().
At first:
testB.prototype = Object.create(testA);
Instantiates a function, you may want to either instantiate the prototype:
testB.prototype = Object.create(testA.prototype);
or construct it directly:
testB.prototype =new testA;
Secondly SomeData is not returning anything, may do so and you also need to keep the context:
testB.prototype.Somedata = function() {
return testA.prototype.get.call(this,"return");
}
Or even easier if we did the upper inheritance right:
testB.prototype.Somedata = function() {
return this.get("return");
}
Your using Object.create against a constructor, you should use it against an instance, otherwise, you get a function in return instead of an object.
var TestA = function() {
this._data = undefined;
};
TestA.prototype.init = function(data) {
this._data = data;
};
TestA.prototype.get = function() {
return this._data;
};
var instance = Object.create(new TestA());
instance.init('some');
instance.get();
I wrote the following code:
var Request = require('./request');
function Treasure(id) {
Treasure.prototype.valid = false;
Treasure.prototype.id = id;
Treasure.prototype.contentLength = 0;
Treasure.prototype.title = null;
Treasure.prototype.seller = null;
Treasure.prototype.buyer = null;
Treasure.prototype.cost = 0;
}
Treasure.prototype.loadData = function() {
EpvpRequest.treasureRequest(Treasure.prototype.id, function(data) {
if (data.valid) {
Treasure.prototype.valid = data.valid;
Treasure.prototype.contentLength = data.contentLength;
Treasure.prototype.title = data.title;
Treasure.prototype.seller = data.seller;
Treasure.prototype.buyer = data.buyer;
Treasure.prototype.cost = data.cost;
}
});
}
module.exports = Treasure;
Please don't hit me, I just started learning javascript.
I want ot access the properties of "Treasure"; but I can't use this, because I have a callback in the loadData function and this would refer to the function which called the callback - is that correct?
But it seems that I can't access the properties the way I tried with Treasure.prototype.property.
What is the correct way to to this?
First of all, you should be assigning instance variables in the constructor instead of assiginng to the prototype. The prototype is for methods and other things that will be shared by all Treasure instances.
function Treasure(id) {
this.valid = false;
this.id = id;
this.contentLength = 0;
this.title = null;
this.seller = null;
this.buyer = null;
this.cost = 0;
}
As for your problem with this inside callbacks, the usual workaround is to store the value of this in a regular variable and then use that variable inside the callback.
Treasure.prototype.loadData = function() {
// Nothing special about "that"
// Its just a regular variable.
var that = this;
EpvpRequest.treasureRequest(that.id, function(data) {
if (data.valid) {
that.valid = data.valid;
that.contentLength = data.contentLength;
that.title = data.title;
that.seller = data.seller;
that.buyer = data.buyer;
that.cost = data.cost;
}
});
}
Since this pattern comes up very often, some people choose to always use the same name for the "this-storage" variable. Some of the more popular names are self and that.
I'm a JS beginner. I have defined a function on my Backbone model as follows.
myFunction: function () {
return {
firstAttr: this.model.get('value-attribute')
};
}
It is available to me as this.myFunction.
From somewhere else in the code, I want to extend this.myFunction to return another attribute. In other words, I'd like it to return a dict with two attributes: { firstAttr: 'something', secondAttr: true }.
How can I do this?
I've tried:
this.myFunction().secondAttr = true;
but I know that's the wrong thing to do.
Assuming your model prototype looks like
var MyModel = Backbone.Model.extend({
myFunction: function () {
return {
// I assume you work directly on a model
// the principle would be the same with a wrapper object
firstAttr: this.get('value-attribute')
};
}
});
you can either mask your method on a model by model basis like this:
var m = new MyModel({'value-attribute': 'attr, the first'});
console.log(m.myFunction());
m.myFunction = function () {
var res = MyModel.prototype.myFunction.call(this);
res.secondAttr = true;
return res;
};
console.log(m.myFunction());
See http://jsfiddle.net/V8zt2/ for a demo
Or dynamically modify your prototype to alter all instances :
var f = MyModel.prototype.myFunction;
MyModel.prototype.myFunction = function () {
var res = f.call(this);
res.secondAttr = true;
return res;
};
var m = new MyModel({'value-attribute': 'attr, the first'});
console.log(m.myFunction());
http://jsfiddle.net/V8zt2/1/
How about modifying your myFunction to :
myFunction : function () {
var i,
obj = {};
for (i=0; i< arguments.length;i++){
obj['attribute'+(i+1)] = this.model.get(arguments[i]);
}
return obj;
}
This way you can send keys of model, that you want to be in the returned object as arguments to myFunction.
What is the difference between this way:
var MyNamespace = window.MyNamespace || {};
MyNamespace.Helper = function()
{
var _getValue = function()
{
var value = 5;
return value;
};
return
{
getValue: _getValue
};
}();
and this way:
var MyNamespace = window.MyNamespace || {};
MyNamespace.Helper = function()
{
function _getValue()
{
var value = 5;
return value;
};
var publicMethod =
{
getValue: function() { _getValue(); }
};
return publicMethod;
};
There are two pretty significant differences:
The first version doesn't return an object, so MyNamespace.Helper will be undefined. Trying to use getValue on it will fail. This is thanks to Automatic Semicolon Insertion adding a ; after the return. Don't put line breaks after return and what it returns.
Assuming you fix that, then calling MyNamespace.Helper.getValue on the first one will give you the value 5, whereas calling it on the second one will give you undefined, because your anonymous wrapper around _getValue doesn't return anything.
I have a very simple function:
var errorsViewModel = function () {
var self = this;
var _errors = ko.observableArray([]);
self.get = function () {
return _errors;
};
self.insert = function ( error ) {
_errors.push(error);
};
}
What I want to acomplish is make _errors array modifiable directly only within its own function. That is users from outside can get the array for reading through the get method and insert itsert items only through the insert method.
But not to be able to do something like this:
var err = new errorsViewModel();
var array = err.get();
array.push('item');
Instead use the errorsViewModel interface :
err.insert('some error');
Is that possible?
Just copy the returned array:
self.get = function () {
return _errors.slice(0);
};
That way, when get is called, the caller can make changes to it if they want - but it won't modify the original.
To make sure that your array isn't accessible from outside your scope I would suggest that you expose the array via a ko.computed and then notify it's listeners on an insert.
var errorsViewModel = function () {
var self = this;
var _errors = [];
self.errors = ko.computed(function () {
return self.get();
});
self.get = function () {
return _errors.splice(0);
};
self.insert = function ( error ) {
_errors.push(error);
self.errors.valueHasMutated();
};
}