Making a javascript knockout viewmodel without the new keyword - javascript

I'm looking through the knockout tutorials, and all the examples create the view model using the 'new' keyword:
//from learn.knockoutjs.com
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
}
ko.applyBindings(new AppViewModel());
I'm trying to avoid using the new keyword, which usually works perfectly ok, but I find trouble getting the fullName computed property to work. This is what I've come up with so far.
function makeViewModel() {
return {
firstName: ko.observable("Bert"),
lastName: ko.observable("Bertington"),
fullName: ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this) };
}
ko.applyBindings(makeViewModel());
...which obviously fails since 'this' no longer refers to the local object inside the function passed to computed. I could get around this by creating a variable and store the view model before attaching the computed function and returning it, but if there exists a more elegant and compact solution that doesn't require me to make sure that methods that depend on each other are attached in the correct order, I'd sure like to use that instead.
Is there a better solution?

You can certainly get around using the new keyword by making the function self invoking, but I think you'd be better off solving the problem of the "this" keyword. I like to show people 3 ways to create viewmodels.
object literal http://jsfiddle.net/johnpapa/u9S93/
as a function http://jsfiddle.net/johnpapa/zBqxy/
with the Revealing Module Pattern http://jsfiddle.net/johnpapa/uRXPn/
When using option 2 or 3 above, it is much easier to deal with the "this" keyword.

When creating it in a function, it is not necessary to return a new object. Instead you would do:
var ViewModel = function() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function() {
this.firstName() + " " + this.lastName();
}, this);
};
Now you have access to the proper this in the computed observable.
If you really do not want to use "new" (there is no reason why you should not in this case), then you could do something like:
var createViewModel = function() {
var result = {
firstName: ko.observable("Bert"),
lastName: ko.observable("Bertington")
};
result.fullName = ko.computed(function() {
return result.firstName() + " " result.lastName();
});
return result;
};

You can enforce new like so (taken from this great pattern resource)
function Waffle() {
if (!(this instanceof Waffle)) {
return new Waffle();
}
this.tastes = "yummy";
}
However I am unsure what you mean by
I'm trying to avoid using the new keyword, which usually works
perfectly ok, but I find trouble getting the fullName computed
property to work. This is what I've come up with so far.
This should work fine, can you show us a concrete example in jsfiddle that doesn't work with using new.
Hope this helps.

Related

How to properly return values when using 'this' in an 'constructor' and the prototype methods of the object?

For live code sample checkout my: Codepen
Question: How can I make sure that p1.prototype.setFirst() & p1.prototype.fullName() return the proper values while still using this?
var Person = function(){
this.firstName = "Penelope";
this.lastName = "Barrymore";
}
Person.prototype.fullName = function () {
return this.firstName + " " + this.lastName;
}
Person.prototype.setFirst = function () {
return this.firstName = "mark"
}
var p1 = new Person();
p1.prototype.setFirst()
console.log(p1.prototype.fullName());
If you really have to call via the prototype like that, you can do:
Person.prototype.setFirst.call(p1);
...and:
Person.prototype.fullName.call(p1);
call and apply are the easiest ways to change this.
If you want reference to a version of a function where this is bound to it, use bind:
var myFullName = Person.prototype.fullName.bind(p1);
myFullName(); // this will be p1
...but of course, this is the natural thing to do:
p1.fullName()
And if you want to get the prototype through the object, you can use:
p1.__proto__
...or:
p1.constructor.prototype

How avoid getter/setter functions in the module pattern when passing arguments

For some time now, I've been structuring my JavaScript Code like this:
;(function() {
function Example(name, purpose) {
this.name = name;
this. purpose = purpose;
}
Example.prototype.getInfo = function() {
return 'The purpose of "' + this.name + '" is: ' + this.purpose;
}
Example.prototype.showInfo = function() {
alert(this.getInfo());
}
var ex = new Example('someModule', 'Showing some stuff.');
ex.showInfo();
})(undefined);
Fiddle
Now I've realized that this pattern is far from ideal as is has some problems:
It doesn't utilize closures/scope so simulate public & private
members.
It doesn't export something, meaning the module itself is not really encapsulated & namespaced.
(Disclaimer: I haven't used it in any bigger project, so I might be missing some important details that occur when working under real live conditions.)
To solve these issues, I started looking into JavaScript design patterns. One of patterns that immediately appealed to me is the module pattern.
I tried to rewrite the code above using the module pattern, but I can't get it quite right:
var Example = (function() {
function getInfo() {
return 'The purpose of "' + name + '" is: ';
}
// Public stuff
return {
name: '',
purpose: '',
setInfo: function(name, purpose) {
this.name = name;
this.purpose = purpose;
},
showInfo: function() {
alert(getInfo());
}
};
})(undefined);
Example.setInfo('someModule', 'Showing some stuff.');
Example.showInfo();
Non working Example: Fiddle
Now the module itself is encapsulated inside the Example namespace & there is something like public & private members, but working with it is quite different & difficult to me, probably because I can't wrap my head around the fact that there is no instance created using the new keyword.
In the non working example, why does it alert result although that string is never set & why is purpose not alerted? I think the setInfo method itself works, so it's probably a scope issue I don't understand.
Also, is there a way around using getter/setter functions? To me it currently looks like assignments I would normally do in the constructor aren't really possible using the module pattern:
function Example(name, purpose) {
this.name = name;
this. purpose = purpose;
}
Using the module pattern, I either have to user getter/setter or something like a 'universal setter function' in form of an init function.
Coming from PHP OOP, I always try to avoid them as much as possible, but I don't really know how to handle that in a prototype based language.
Maybe there is something similar to the module pattern, but with using prototypes – something like module & constructor pattern? It might be easier for me to understand.
Use it this way and it should work and you are right, this is scope issue.
Here is the working fiddle
Notice that I have taken snapshot of this in a variable and am using that. It is usually done in order to keep a reference to this when the context is changing.
No use of new Keyword
In your case returning {} is returning a new instance of anonymous object with properties as defined. Hence, you do not need new keyword also. You can take a look at this for anonymous objects.
When you use this, the scope of this changes in return {} object and they no more refer to the Example object.
Using getter / setter function
You don't need them. assignments would do, but remember, the variables would be attached with self so you would need to do self.name = name and self.purpose = purpose in order to do assignments or get values.
var Example = (function() {
var self = this;
function getInfo() {
return 'The purpose of "' + name + '" is: ' + purpose;
}
// Public stuff
return {
name: '',
purpose: '',
setInfo: function(name, purpose) {
self.name = name;
self.purpose = purpose;
},
showInfo: function() {
alert(getInfo());
}
};
})(undefined);
Example.setInfo('someModule', 'Showing some stuff.');
Example.showInfo();
Update:
Fiddle wasn't saved properly I have updated that. Also In there I just corrected your code.
I think this is what you are trying to achieve:
var Example = (function (params) {
var self = this;
self.name = params.name;
self.purpose = params.purpose;
function getInfo() {
return 'The purpose of "' + self.name + '" is: ' + self.purpose;
};
self.showInfo(alert(getInfo()));
return{
};
});
var myExample = new Example({
name: 'someModule',
purpose: 'somePurpose'
});
myExample.showInfo();
I'm not sure if that's what you're trying to achieve:
http://jsfiddle.net/Ly66mcxo/1/
Example = (function() {
var _name, _purpose;
function getInfo() {
return 'The purpose of "' + _name + '" is: ' + _purpose;
}
// Public stuff
return {
setInfo: function(name, purpose) {
_name = name;
_purpose = purpose;
},
showInfo: function() {
alert(getInfo());
}
};
})(undefined);
Example.setInfo('someModule', 'Showing some stuff.');
Example.showInfo();
Check now
var Example = (function () {
var _this = this;
_this.getInfo = function () {
return 'The purpose of "' + _this.name + '" is: ' + _this.purpose;
}
return {
setInfo: function (name, purpose) {
_this.name = name;
_this.purpose = purpose;
},
showInfo: function () {
alert(_this.getInfo());
}
};
})(undefined);
Example.setInfo('someModule', 'Showing some stuff.');
Example.showInfo();

What is the difference between these three module pattern implementations in JavaScript?

I've seen the following three code blocks as examples of the JavaScript module pattern. What are the differences, and why would I choose one pattern over the other?
Pattern 1
function Person(firstName, lastName) {
var firstName = firstName;
var lastName = lastName;
this.fullName = function () {
return firstName + ' ' + lastName;
};
this.changeFirstName = function (name) {
firstName = name;
};
};
var jordan = new Person('Jordan', 'Parmer');
Pattern 2
function person (firstName, lastName) {
return {
fullName: function () {
return firstName + ' ' + lastName;
},
changeFirstName: function (name) {
firstName = name;
}
};
};
var jordan = person('Jordan', 'Parmer');
Pattern 3
var person_factory = (function () {
var firstName = '';
var lastName = '';
var module = function() {
return {
set_firstName: function (name) {
firstName = name;
},
set_lastName: function (name) {
lastName = name;
},
fullName: function () {
return firstName + ' ' + lastName;
}
};
};
return module;
})();
var jordan = person_factory();
From what I can tell, the JavaScript community generally seems to side with pattern 3 being the best. How is it any different from the first two? It seems to me all three patterns can be used to encapsulate variables and functions.
NOTE: This post doesn't actually answer the question, and I don't consider it a duplicate.
I don't consider them module patterns but more object instantiation patterns. Personally I wouldn't recommend any of your examples. Mainly because I think reassigning function arguments for anything else but method overloading is not good. Lets circle back and look at the two ways you can create Objects in JavaScript:
Protoypes and the new operator
This is the most common way to create Objects in JavaScript. It closely relates to Pattern 1 but attaches the function to the object prototype instead of creating a new one every time:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
Person.prototype.fullName = function () {
return this.firstName + ' ' + this.lastName;
};
Person.prototype.changeFirstName = function (name) {
this.firstName = name;
};
var jordan = new Person('Jordan', 'Parmer');
jordan.changeFirstName('John');
Object.create and factory function
ECMAScript 5 introduced Object.create which allows a different way of instantiating Objects. Instead of using the new operator you use Object.create(obj) to set the Prototype.
var Person = {
fullName : function () {
return this.firstName + ' ' + this.lastName;
},
changeFirstName : function (name) {
this.firstName = name;
}
}
var jordan = Object.create(Person);
jordan.firstName = 'Jordan';
jordan.lastName = 'Parmer';
jordan.changeFirstName('John');
As you can see, you will have to assign your properties manually. This is why it makes sense to create a factory function that does the initial property assignment for you:
function createPerson(firstName, lastName) {
var instance = Object.create(Person);
instance.firstName = firstName;
instance.lastName = lastName;
return instance;
}
var jordan = createPerson('Jordan', 'Parmer');
As always with things like this I have to refer to Understanding JavaScript OOP which is one of the best articles on JavaScript object oriented programming.
I also want to point out my own little library called UberProto that I created after researching inheritance mechanisms in JavaScript. It provides the Object.create semantics as a more convenient wrapper:
var Person = Proto.extend({
init : function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
},
fullName : function () {
return this.firstName + ' ' + this.lastName;
},
changeFirstName : function (name) {
this.firstName = name;
}
});
var jordan = Person.create('Jordan', 'Parmer');
In the end it is not really about what "the community" seems to favour but more about understanding what the language provides to achieve a certain task (in your case creating new obejcts). From there you can decide a lot better which way you prefer.
Module patterns
It seems as if there is some confusion with module patterns and object creation. Even if it looks similar, it has different responsibilities. Since JavaScript only has function scope modules are used to encapsulate functionality (and not accidentally create global variables or name clashes etc.). The most common way is to wrap your functionality in a self-executing function:
(function(window, undefined) {
})(this);
Since it is just a function you might as well return something (your API) in the end
var Person = (function(window, undefined) {
var MyPerson = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
MyPerson.prototype.fullName = function () {
return this.firstName + ' ' + this.lastName;
};
MyPerson.prototype.changeFirstName = function (name) {
this.firstName = name;
};
return MyPerson;
})(this);
That's pretty much modules in JS are. They introduce a wrapping function (which is equivalent to a new scope in JavaScript) and (optionally) return an object which is the modules API.
First, as #Daff already mentioned, these are not all module patterns. Let's look at the differences:
Pattern 1 vs Pattern 2
You might omit the useless lines
var firstName = firstName;
var lastName = lastName;
from pattern 1. Function arguments are already local-scoped variables, as you can see in your pattern-2-code.
Obviously, the functions are very similar. Both create a closure over those two local variables, to which only the (exposed) fullName and the changeFirstName functions have access to. The difference is what happens on instantiation.
In pattern 2, you just return an object (literal), which inherits from Object.prototype.
In pattern 1, you use the new keyword with a function that is called a "constructor" (and also properly capitalized). This will create an object that inherits from Person.prototype, where you could place other methods or default properties which all instances will share.
There are other variations of constructor patterns. They might favor [public] properties on the objects, and put all methods on the prototype - you can mix such. See this answer for how emulating class-based inheritance works.
When to use what? The prototype pattern is usually preferred, especially if you might want to extend the functionality of all Person instances - maybe not even from the same module. Of course there are use cases of pattern 1, too, especially for singletons that don't need inheritance.
Pattern 3
…is now actually the module pattern, using a closure for creating static, private variables. What you export from the closure is actually irrelevant, it could be any fabric/constructor/object literal - still being a "module pattern".
Of course the closure in your pattern 2 could be considered to use a "module pattern", but it's purpose is creating an instance so I'd not use this term. Better examples would be the Revealing Prototype Pattern or anything that extends already existing object, using the Module Pattern's closure - focusing on code modularization.
In your case the module exports a constructor function that returns an object to access the static variables. Playing with it, you could do
var jordan = person_factory();
jordan.set_firstname("Jordan");
var pete = person_factory();
pete.set_firstname("Pete");
var guyFawkes = person_factory();
guyFawkes.set_lastname("Fawkes");
console.log(jordan.fullname()); // "Pete Fawkes"
Not sure if this was expected. If so, the extra constructor to get the accessor functions seems a bit useless to me.
"Which is best?" isn't really a valid question, here.
They all do different things, come with different trade-offs, and offer different benefits.
The use of one or the other or all three (or none) comes down to how you choose to engineer your programs.
Pattern #1 is JS' traditional take on "classes".
It allows for prototyping, which should really not be confused with inheritance in C-like languages.
Prototyping is more like public static properties/methods in other languages.
Prototyped methods also have NO ACCESS TO INSTANCE VARIABLES (ie: variables which aren't attached to this).
var MyClass = function (args) { this.thing = args; };
MyClass.prototype.static_public_property = "that";
MyClass.prototype.static_public_method = function () { console.log(this.thing); };
var myInstance = new MyClass("bob");
myInstance.static_public_method();
Pattern #2 creates a single instance of a single object, with no implicit inheritance.
var MyConstructor = function (args) {
var private_property = 123,
private_method = function () { return private_property; },
public_interface = {
public_method : function () { return private_method(); },
public_property : 456
};
return public_interface;
};
var myInstance = MyConstructor(789);
No inheritance, and every instance gets a NEW COPY of each function/variable.
This is quite doable, if you're dealing with objects which aren't going to have hundreds of thousands of instances per page.
Pattern #3 is like Pattern #2, except that you're building a Constructor and can include the equivalent of private static methods (you must pass in arguments, 100% of the time, and you must collect return statements, if the function is intended to return a value, rather than directly-modifying an object or an array, as these props/methods have no access to the instance-level data/functionality, despite the fact that the instance-constructor has access to all of the "static" functionality).
The practical benefit here is a lower memory-footprint, as each instance has a reference to these functions, rather than their own copy of them.
var PrivateStaticConstructor = function (private_static_args) {
var private_static_props = private_static_args,
private_static_method = function (args) { return doStuff(args); },
constructor_function = function (private_args) {
var private_props = private_args,
private_method = function (args) { return private_static_method(args); },
public_prop = 123,
public_method = function (args) { return private_method(args); },
public_interface = {
public_prop : public_prop,
public_method : public_method
};
return public_interface;
};
return constructor_function;
};
var InstanceConstructor = PrivateStaticConstructor(123),
myInstance = InstanceConstructor(456);
These are all doing very different things.

Difference between knockout View Models declared as object literals vs functions

In knockout js I see View Models declared as either:
var viewModel = {
firstname: ko.observable("Bob")
};
ko.applyBindings(viewModel );
or:
var viewModel = function() {
this.firstname= ko.observable("Bob");
};
ko.applyBindings(new viewModel ());
What's the difference between the two, if any?
I did find this discussion on the knockoutjs google group but it didn't really give me a satisfactory answer.
I can see a reason if I wanted to initialise the model with some data, for example:
var viewModel = function(person) {
this.firstname= ko.observable(person.firstname);
};
var person = ... ;
ko.applyBindings(new viewModel(person));
But if I'm not doing that does it matter which style I choose?
There are a couple of advantages to using a function to define your view model.
The main advantage is that you have immediate access to a value of this that equals the instance being created. This means that you can do:
var ViewModel = function(first, last) {
this.first = ko.observable(first);
this.last = ko.observable(last);
this.full = ko.computed(function() {
return this.first() + " " + this.last();
}, this);
};
So, your computed observable can be bound to the appropriate value of this, even if called from a different scope.
With an object literal, you would have to do:
var viewModel = {
first: ko.observable("Bob"),
last: ko.observable("Smith"),
};
viewModel.full = ko.computed(function() {
return this.first() + " " + this.last();
}, viewModel);
In that case, you could use viewModel directly in the computed observable, but it does get evaluated immediate (by default) so you could not define it within the object literal, as viewModel is not defined until after the object literal closed. Many people don't like that the creation of your view model is not encapsulated into one call.
Another pattern that you can use to ensure that this is always appropriate is to set a variable in the function equal to the appropriate value of this and use it instead. This would be like:
var ViewModel = function() {
var self = this;
this.items = ko.observableArray();
this.removeItem = function(item) {
self.items.remove(item);
}
};
Now, if you are in the scope of an individual item and call $root.removeItem, the value of this will actually be the data being bound at that level (which would be the item). By using self in this case, you can ensure that it is being removed from the overall view model.
Another option is using bind, which is supported by modern browsers and added by KO, if it is not supported. In that case, it would look like:
var ViewModel = function() {
this.items = ko.observableArray();
this.removeItem = function(item) {
this.items.remove(item);
}.bind(this);
};
There is much more that could be said on this topic and many patterns that you could explore (like module pattern and revealing module pattern), but basically using a function gives you more flexibility and control over how the object gets created and the ability to reference variables that are private to the instance.
I use a different method, though similar:
var viewModel = (function () {
var obj = {};
obj.myVariable = ko.observable();
obj.myComputed = ko.computed(function () { return "hello" + obj.myVariable() });
ko.applyBindings(obj);
return obj;
})();
Couple of reasons:
Not using this, which can confusion when used within ko.computeds etc
My viewModel is a singleton, I don't need to create multiple instances (i.e. new viewModel())

Object Creation in javascript

Just for the kicks i am trying to create a simple data object in javascript. Here is the code.
var roverObject = function(){
var newRover = {};
var name;
var xCord;
var ycord;
var direction;
newRover.setName = function(newName) {
name = newName;
};
newRover.getName = function() {
return name;
};
newRover.setDirection = function(newDirection) {
direction = newDirection;
};
newRover.getDirection = function() {
return direction;
};
newRover.setXCord = function(newXCord) {
xCord = newXCord;
};
newRover.getXCord = function() {
return xCord;
};
newRover.setYCord = function(newYCord) {
yCord = newYCord;
};
newRover.getYCord = function() {
return yCord;
};
newRover.where = function(){
return "Rover :: "+ name +" is at Location("+xCord+","+yCord+") pointing to "+direction;
};
return newRover;
};
rover1 = new roverObject();
rover2 = new roverObject();
rover1.setName("Mars Rover");
rover1.setDirection("NORTH");
rover1.setXCord(2);
rover1.setYCord(2);
console.log(rover1.where());
console.log(rover1);
rover2.setName("Moon Rover");
rover2.setDirection("SOUTH");
rover2.setXCord(1);
rover2.setYCord(1);
console.log(rover2.where());
console.log(rover2);
There are few questions that I have around this creation.
I want to create an object where the properties/attributes of object are private and not visible to world. Am I successful in doing that? Can I really not access the object attributes?
Is there a better way to create this kind of object?
If I want to inherit this object, I should do a newObject.prototype = roverObjectwill that work? And will that make sense most of all.
Finally I have a wierd problem. Notice the last method of objet "where" which returns a concatenated string. Here I tried following code instead.
newRover.where = function(){
return "Rover :: "+ name +" is at Location("+xCord+","+yCord+") pointing to "+direction;
}();
and then did a following console.log
console.log(rover1.where);
console.log(rover2.where);
It threw following error for me:
cannot access optimized closure
Why would it say that? What am I doing wrong?
Thanks for all the help. Any review comments would be appreciated too!
Cheers
Am I successful in doing that? Can I really not access the object attributes?
Indeed. You don't have object attributes, you have local variables in the roverObject function. Local variables can't be accessed from outside, only from the functions inside the roverObject function that have a closure over them.
That you are calling roverObject as a constructor, with new roverObject, is irrelevant, as you are returning a different object from the function. Saying var rover1= roverObject() without the new would do exactly the same thing. Notably the object returned by [new] roverObject is a plain Object as you created it from {}; rover1 instanceof roverObject is false.
If you wanted instanceof to work, you would have to call with new, and use this instead of newRover in the constructor function.
If I want to inherit this object, I should do a newObject.prototype = roverObject will that work? And will that make sense most of all.
No. You currently have no allowance for prototyping. You are using a separate copy of each method for each instance of the roverObject. You can do certainly objects this way but it's a different approach than prototyping. If you wanted to make something like a subclass of roverObject in the arrangement you have now, you'd say something like:
function AdvancedRover() {
var rover= new roverObject();
rover.doResearch= function() {
return rover.where()+' and is doing advanced research';
};
return rover;
}
Note since the ‘private’ local variables in the base class constructor really are private, even the subclass cannot get at them. There's no ‘protected’.
newRover.where = function(){ ... }();
What's that trying to do? I can't get the error you do; all the above does is assigns the string with the location to where (before the setter methods have been called, so it's full of undefineds).
Is there a better way to create this kind of object?
Maybe. see this question for a discussion of class/instance strategies in JavaScript.
Q1: you can create 'private' members in javascript 'classes'. In javascript, privacy is not determined by any access specifier. Instead, access needs to be specifically instrumented. Example:
function MyClass() {
this.val = 100; // public;
var privateVal = 200;
function getVal() { return this.val; } // private method;
this.getPrivateVal = function() { // public method, accessor to private variable
return privateVal;
}
}
Object scope in javascript is governed by a queer concept called closures. AFAIK, there is no parallel concept in any other popular launguage like C+/Java etc.
While I understand what closures are, I cannot put it in words. Perhaps a demonstration will help you:
function closureDemo() {
var done=false;
function setDone() { done=true; }
doLater(setDone);
}
function doLater(func) { setTimeout(func,1000); }
closureDemo();
now, while setDone is called from within doLater, it can still access done in closureDemo, even though done is not in scope (in the conventional procedural sense).
I think you will understand more when you read this.
Q2: I can only say what I do; I don't know if it is better or not. If I wrote your code, it would look like this:
function RoverObject() {
var newRover = {}; // privates
var name;
var xCord;
var ycord;
var direction;
this.setName = function(newName) {
name = newName;
};
this.getName = function() {
return name;
};
this.setDirection = function(newDirection) {
direction = newDirection;
};
// and so on...
this.where = function(){
return "Rover :: "+ name +" is at Location("+xCord+","+yCord+") pointing to "+direction;
};
}
var rover1 = new RoverObject();
Points to note:
capitalization of "class name"'s first letter
use of this instead of roverObject
this function is a pure constructor. it returns nothing.
Q3: if you want to do inheritance, then my method (use of this) will not work. Instead, the public methods should be a part of the prototype of RoverObject. Read this. Excellent material.
Hope that helps.
EDIT: There is a problem with the way your code is doing work. Problems:
your function does not do what its name suggests. Its name had better be createRoverObject, because that's exactly what it is doing. It is not working like a class constructor
the methods supported by your class are part of the object, but the data members are not. While this may work (and it is not, as your console.log() problem suggests), it is not a good way to implement a class in javascript. The problem here is of closures. Again, i'm unable to articulate what the problem specifically is, but I can smell it.
With regards to 4. - you are trying to log the function, not the result of calling the function. Should be console.log(rover1.where()); My guess firebug(I assume it's firebug's console.log) does not like to log function definitions.
EDIT Oh I get it, you are actually executing the where funcion when you assign rover.where. Are you trying to get what looks like a property to actually be a function? If that's the case it won't work. It will have to be a function if you want it to be evaluated when it's called.
What happens in you case where gets executed in the constructor function. At that point you are still creating the roverObject closure and hence it's too early to access it's private variables.
This is just addressing point 1 of your post.
Here's a good article on javascript private members and more:
Private Members in JavaScript
Defining your object like this gives you private members.
function RolloverObject() {
var name;
var xCord;
var ycord;
var direction;
this.setName = function(newName) { name = newName; };
this.getName = function() { return name; };
this.setDirection = function(newDirection) { direction = newDirection; };
this.getDirection = function() { return direction; };
this.setXCord = function(newXCord) { xCord = newXCord; };
this.getXCord = function() { return xCord; };
this.setYCord = function(newYCord) { yCord = newYCord; };
this.getYCord = function() { return yCord; };
this.where = function() {
return "Rover :: " + name + " is at Location(" + xCord + "," + yCord + ") pointing to " + direction;
};
}
var rolloverObject = new RolloverObject();

Categories

Resources