Cannot figure out why I am getting the error that stats is not defined when it is...
I have tried naming and renaming and calling the previously named function still getting the error
function GameObject(GO){
this.createdAt = GO.createdAt;
this.name = GO.name;
this.dimensions = GO.dimensions;
}
GameObject.prototype.destroy = function(){
return `${this.name} was removed from the game.`;
}
function CharacterStats(stats){
GameObject.call(stats);
this.healthPoints= stats.healthPoints
}
CharacterStats.prototype = Object.create(GameObject.prototype)
CharacterStats.prototype = takeDamage = function(){
return `${this.name} took damage`;
}
function Humanoid(PettyHumans){
this.team = PettyHumans.team;
this.weapons = PettyHumans.weapons;
this.language = PettyHumans.language;
CharacterStats.call(this.PettyHumans)
}
Humanoid.prototype.greet = function(){
return `${this.name} offers a greeting in ${this.language}.`;
}
This code passes undefined to CharacterStats:
function Humanoid(PettyHumans){
this.team = PettyHumans.team;
this.weapons = PettyHumans.weapons;
this.language = PettyHumans.language;
CharacterStats.call(this.PettyHumans)
// ^^^^-------------- The problem is here
}
Assuming you call Humanoid via new Humanoid, you haven't set that property anywhere. PettyHumans is a parameter, not a property. Either set it as a property, or remove the this. from that line.
Side note: In a couple of places it looks like you're trying to implement class-like inheritance (for instance, between CharacterStats and GameObject), but the code doing that isn't quite correct. See this answer (which I also wrote) for how to correct it, either continuing with ES5 syntax or using ES2015+ class syntax. But briefly, the minimal change to make it correct is to add a line:
GameObject.call(stats);
this.healthPoints = stats.healthPoints
}
CharacterStats.prototype = Object.create(GameObject.prototype)
CharacterStats.prototype.constructor = CharacterStats // Add this (and similar when doing other inheritance)
Or, again, use class. (You can transpile if you need to support ES5-only JavaScript engines.)
Related
I have picked up a piece of software which is fairly old and it has this form of "class" definition
function thisThing(parm1, parm2)
{
var self = new BaseThing(parm1);
self.val2 = parm2;
self.function2 = function() { ... }
return self;
}
I'd like to convert the whole hierachy to use the thisThing.prototype style of class, something like this
function thisThing(parm1, parm2)
{
var self = new BaseThing(parm1);
self.val2 = parm2;
return self;
}
thisThing.prototype = Object.create(BaseThing.prototype);
thisThing.prototype.constructor = thisThing;
thisThing.prototype = {
function2() { ... }
}
but I'm not sure if it is safe to mix the two styles.
Do I have to convert the whole hierarchy at once? Or can I do it a class at a time, and in which case do I need to do it top up, bottom down, or can I do it in the order I come across classes?
A note: Please don't suggest using ES6 classes, as they are not available in my current environment.
You've said that the old thisThing is called via new, which is good news in terms of whether you can mix things together (although we could work around it if not).
What you've shown as your desired form is quite non-standard, and thisThing.prototype is never used in it. I'm going to assume you mean you want to use standard constructor functions, which look like this:
function ThisThing(parm1, parm2) {
BaseThing.call(this, parm1);
this.parm2 = parm2;
}
ThisThing.prototype = Object.create(BaseThing.prototype);
ThisThing.prototype.constructor = ThisThing;
ThisThing.prototype.someMethod = function() {
// ...
};
Based on what you have in the question, you can go ahead and do that. (I do recommend the change in capitalization, it's the overwhelming standard for constructor functions.)
If there's any chance code might be calling it without new, you can make it tolerate that by detecting what's happened and handing off to new in the constructor:
function ThisThing(parm1, parm2) {
if (!(this instanceof ThisThing)) {
// Called without `new`; handle it
return new ThisThing(parm1, parm2);
}
BaseThing.call(this, parm1);
this.parm2 = parm2;
}
// ...
The thisThing you showed was using BaseThing as a constructor, so I assume (from that and the name) that it's already using the constructor pattern above.
You should be able to replace it like this. The only issue might be setting the param1 is a new BaseThing, so you might need to modify your old code.
by doing this you are using prototypical inheritance to get the methods of BaseThing.
Conversion like this can be mixed with your existing code with no problems so you can change one class at a time.
function ThisThing(param1, param2) {
this.val1 = param1
this.val2 = param2
}
ThisThing.prototype = new BaseThing
ThisThing.prototype.function2 = function() {}
var thing = new ThisThing(1, 2)
console.log(
thing instanceof BaseThing, // => true
thing instanceof ThisThing // => true
)
I use the iOS UI Automation framework to make sure my iPhone app rocks.
Everybody who uses this framework would tell you that it's great, but that it's lacking a lot of structure.
So I have to deal with instances of UIAWindow, which represent different screens of my app. To be more object-oriented, I'd like to have a specific class for each screen, so I could add specific methods, like
myScreen1.tapDoneButton();
var total = myScreen2.getNumberOfElements();
For the moment, I'm able to achieve this by passing the instances of UIAWindow to functions that will add the appropriate methods, like this :
function makeMainScreen(actualScreen)
{
actualScreen.constructor.prototype.getAddButton = function() {
return this.buttons()["add button"];
};
actualScreen.constructor.prototype.tapAddButton = function() {
this.getAddButton().tap();
};
// Add any desired method...
return actualScreen;
}
It works fine, I use it like this :
var mainScreen = makeMainScreen(app.mainWindow());
mainScreen.tapAddButton();
But that doesn't seem object-oriented enough, I would like to create real objects, using the new and this keywords, so I'd have a declaration like this :
function MainScreen(actualScreen){
// This line doesn't work : because 'this' is immutable
this = actualScreen;
this.tapAddButton = function(){
this.getAddButton().tap();
}
//...
}
And I'd use it like this :
var mainScreen = new MainScreen(app.mainWindow());
mainScreen.tapAddButton();
I thought I could save the actualScreen as a property of the object (Like in Grace Shao's answer below), and call all the methods on it, but I'd like keep the original UIAWindow methods.
Does anybody know how to do this?
Or perhaps what I'm trying to achieve doesn't make sense, in which case I'd be happy to know.
If I understand correctly, you could try the following:
function MainScreen(actualScreen){
this.screen = actualScreen;
}
MainScreen.prototype.tapAddButton = function () {
this.screen.getAddButton().tap();
};
MainScreen.prototype.getScreen = function () {
return this.screen;
};
//...
var mainScreen = new MainScreen(app.mainWindow());
mainScreen.tapAddButton();
You are correct that you cannot assign anything to this. You could also define the methods inside the constructor MainScreen, but they would be considered privileged members.
function MainScreen(actualScreen){
this.screen = actualScreen;
this.tapAddButton = function () {
this.screen.getAddButton().tap();
};
}
If you dont want them to be privileged members, it is better to define them outside the constructor. Otherwise, the members will be initialized over and over again everytime when you instantiate a new object.
Updated:
You could also wrappers for the methods of screen inside the constructor as below.
var prop;
for (prop in actualScreen) {
if (typeof actualScreen[prop] !== 'Function') {
continue;
}
this[prop] = function () {
return actualScreen[prop].apply(actualScreen, arguments);
};
}
I have some js code here link deleted
If you open your js console and you'll run this code snipet
var r = new TempPopupForm("xxx");
r.create();
an error will appear
TypeError: this.init is not a function
this error is saying there is no init method implemented on this object.
But that's not true.As you can see in the code below the init method is declared.
TempPopupForm.prototype = new PopupForm();
TempPopupForm.prototype.constructor = TempPopupForm;
TempPopupForm.superclass = PopupForm.prototype;
function TempPopupForm(name) {
this.init(name);
}
TempPopupForm.prototype.init = function(name) {
TempPopupForm.superclass.init.call(this, name);
};
I guess something is wrong with the inheritance definition,but I can not figure out what it is.
BTW There are some third party dependencies.
EDIT
I was following this article and where the funcs are ordered like I have. The order actually works on the other classes, but not on this one.
http://www.kevlindev.com/tutorials/javascript/inheritance/inheritance10.htm
You need to re-order your functions and instantiation. Since your constructor is using one of its own prototyped method to init, they both need to be above the block where you instantiate the object. JavaScript hoists top-level functions.
Try this -
function TempPopupForm(name) {
this.init(name);
}
TempPopupForm.prototype = new PopupForm();
TempPopupForm.prototype.constructor = TempPopupForm;
TempPopupForm.superclass = PopupForm.prototype;
TempPopupForm.prototype.init = function(name) {
TempPopupForm.superclass.init.call(this, name);
};
var r = new TempPopupForm("xxx");
r.create();
The code below is adapted from this answer
function MessageClass() {
var self = this;
this.clickHander = function(e) { self.someoneClickedMe = true; };
var _private = 0;
this.getPrivate = function() { return _private; };
this.setPrivate = function(val) { _private = val; };
}
ErrorMessageClass.prototype = new MessageClass();
function ErrorMessageClass() {
MessageClass.apply(this, arguments);
}
var errorA = new ErrorMessageClass();
var errorB = new ErrorMessageClass();
errorA.setPrivate('A');
errorB.setPrivate('B');
console.log(errorA.getPrivate());
console.log(errorB.getPrivate());
The original post did not have the MessageClass.apply(this, arguments); since the purpose was to show how inheritance can go wrong in Javascript.
My question is, is saying: ErrorMessageClass.prototype = new MessageClass(); before the ErrorMessageClass constructor has even been declared bad practice? My understanding is that calling undeclared identifiers like that causes a silent declaration to occur, with the result being placed on the global window object, which I understand is bad.
Is this form:
function ErrorMessageClass() {
MessageClass.apply(this, arguments);
}
ErrorMessageClass.prototype = new MessageClass();
considered to be better practice? This link shows the code written as it was originally above, which is why I even tried it. Does this blogger know something I don't (quite likely)?
EDIT
Lots of great info in the answers below, but I did want to highlight this link which really explains things perfectly
Usually, to avoid this confusion, you would just attach the prototype after, but as Adam Rackis pointed out, function declarations are hoisted, like var statements.
However, you should not instantiate the base object as the prototype. If your base object takes arguments, what are you supposed to use? Use an empty "surrogate" constructor
// Used to setup inheritance
function surrogate () {};
function MessageClass() {
var self = this;
this.clickHander = function(e) { self.someoneClickedMe = true; };
var _private = 0;
this.getPrivate = function() { return _private; };
this.setPrivate = function(val) { _private = val; };
}
// The key steps to creating clean inheritance
surrogate.prototype = MessageClass;
// Sets up inheritance without instantiating a base class object
ErrorMessageClass.prototype = new surrogate();
// Fix the constructor property
ErrorMessageClass.prototype.constructor = ErrorMessageClass
function ErrorMessageClass() {
MessageClass.apply(this, arguments);
}
There's much more to be said. http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html
It works because function declarations are evaluated first. If you tried to move these classes under an object literal "namespace" the first version would fail.
I personally find the second method to be much easier to read - also, don't forget to set the sub-class' prototype.constructor property back to itself. Personally, I use an inherits() method on the Function prototype which wraps up essentially the type of code you're using here.
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();