I try to implement the Vector3 class in JS and wrote
function Vector(x,y,z) {
this.x=x;
this.y=y;
this.z=z;
}
so far looks alright, but then I wanted to add the Vector.prototype the function addVector:
Vector.prototype.addVector(addx,addy,addz) = function(addx,addy,addz) {
x+=addx; y+=addy; z+=addz;
};
but then I receive an error:
ReferenceError at line NaN: addx is not defined
I'm new to JS and I wonder what exactly I'm mistyping.
Replace:
Vector.prototype.addVector(addx,addy,addz) =
With:
Vector.prototype.addVector =
That's not where you specify the parameters.
The problem is with the syntax. The following should do your job.
Vector.prototype.addVector = function(addx,addy,addz){
x+=addx;
y+=addy;
z+=addz;
};
Correct your syntax
Vector.prototype.addVector = function (addx, addy, addz) {
this.x+=addx;
this.y+=addy;
this.z+=addz;
}
check here for reading more about prototypes.
You have several correct answers already but let me expand on them for you with a simple visual example so you can learn; it seems you may be unfamiliar with JavaScript prototypes.
// Here is a new function or in this case class
function Person() {};
// This is one way we could add methods to the Person() class
// After you call this method Person() will now have firstName,
// lastName, and age properties
Person.prototype.recordInfo = function(fname,lname,age){
this.firstName = fname;
this.lastName = lname;
this.age = age;
}
If you wan't to keep things together a bit more and have a lot of methods you'll be adding to the Person() class you can also declare your methods like so:
Person.prototype = {
recordInfo: function(fname,lname,age){
this.firstName = fname;
this.lastName = lname;
this.age = age;
},
aNewMethod: function(){
// ...
},
bNewMethod: function(){
// ...
}
}; // <-- Notice the closing semicolon and the commas separating the methods above
Related
I've been reading articles about bind, call, apply for almost a week now and it's still complex for me. I think I need them for this jsfiddle I wrote. However, I wasn't able to since I'm still confused.
I tried my best to write a fiddle of what I heard last week from one of our developers experiencing the issue. He wanted to display the properties of classA from a new class(classC) he made but it wasn't showing the data.
So here it goes.
There is a parent object(classA) that contains the complete properties and methods. A child(subclass like classB) of it inherits the properties from classA so inherited data plus its own data can be rendered on classB's modal.
Now, there is a requirement to add a new modal or section to display few properties from classA and properties from classB. So they made a new class called classC which inherits all information from classB. I remember they said, classC was inheriting all the properties and methods from classB but the properties it needs in classA weren't there.
Please help me with my fiddle. It will help me become a better Javascript developer. Oh, I also remember they were mentioning things like 'call' and 'super' which I am not familiar yet.
function classA() {
this.firstname = 'Donna';
this.lastname = 'Hill';
function getFullname () {
return firstname + ' ' + lastname;
}
}
function classB() {
var childofA = new classA();
var age = 10;
var sex = "female";
var bObject = {
showFullname : function() {
console.log(this.childofA.getFullname);
}
}
return bObject;
}
function classC() {
var childofB = new classB();
var cObject = {
showFullname : function() {
console.log(this.childofB.showFullname);
}
}
return cObject;
}
var c = new classC();
console.log(c.showFullname());
http://jsfiddle.net/01hz8933/2/
Fiddle Updated. http://jsfiddle.net/01hz8933/4/
// setup base class
function ClassA() {
this.firstname = 'Donna';
this.lastname = 'Hill';
}
ClassA.prototype.showFullname = function() {
return this.firstname + ' ' + this.lastname;
}
// first child class
function ClassB() {
this.age = 10;
this.sex = "female";
ClassA.call(this); // call parent constructor
}
ClassB.prototype = Object.create(ClassA.prototype); // inherit
ClassB.prototype.constructor = ClassB; // use our constructor function
// grand child
function ClassC() {
ClassB.call(this); // call parent constructor
}
ClassC.prototype = Object.create(ClassB.prototype); // inherit
ClassC.prototype.constructor = ClassC; // use our constructor function
var c = new ClassC();
console.log(c.showFullname());
There's a ton to unpack in there, but there were many things in your original that were surprising to me. Hopefully the updated fiddle provides some answers for you.
I am looking for a perfect way to define class. "perfect" here means:`
create instances will not create copies of methods.
public function could easily(not to much hassle) access private variable
For example, way 1:
function Foo1() {
var private1;
this.publicMethod1 = function() {//create instance will create copy of this function}
}
will not meet rule No.1 above.
Another example, way 2:
function Foo2() {
var private2;
}
Foo2.prototype.Method2 = function() {//cannot access private2}
will not meet rule No.2 above.
So is it possible to meet both rules? Thanks.
In JavaScript it's more about conventions. Private properties or methods are defined with a underscore first like _private. With a few helpers you can make classes easily. I find this setup easy enough, all you need is a helper inherits to extend classes, and instead of using multiple arguments you pass in an object props and simply call "super" on the inherited classes with arguments. For example, using a module pattern:
Function.prototype.inherits = function(parent) {
this.prototype = Object.create(parent.prototype);
};
var Person = (function PersonClass() {
function Person(props) {
this.name = props.name || 'unnamed';
this.age = props.age || 0;
}
Person.prototype = {
say: function() {
return 'My name is '+ this.name +'. I am '+ this.age +' years old.';
}
};
return Person;
}());
var Student = (function StudentClass(_super) {
Student.inherits(_super);
function Student(props) {
_super.apply(this, arguments);
this.grade = props.grade || 'untested';
}
Student.prototype.say = function() {
return 'My grade is '+ this.grade +'.';
};
return Student;
}(Person));
var john = new Student({
name: 'John',
age: 25,
grade: 'A+'
});
console.log(JSON.stringify(john)); //=> {"name":"John","age":25,"grade":"A+"}
console.log(john.say()); //=> "My grade is A+"
About the private variable "issue" just stick to convention for instance properties and use closures when needed for everything else private.
function Foo3() {
this.private = {};
}
Foo3.prototype.set_x = function (x) {
this.private.x = x;
};
To make a long story short: no, it is not. You cannot extend the prototype with methods that could access private variables. At least if these private variables are made private via a closure.
Though, it is a convention in javascript that you mark your private fields with an underscore, for example _myPrivateField. These would be still public, but i have seen this solution being used in many libraries and i also prefer that style to meet your first rule.
A basic example is below:
Foo = function(id)
{
// private instances.
var _id;
var _self = this;
// constructor
_id = id;
// private method
function _get()
{
return _id;
};
// public function
_self.set = function(id)
{
_id = id;
};
_self.get = function()
{
return _get();
};
};
var bar = Foo(100);
console.log( bar.get() );
bar.set(1000);
console.log( bar.get() );
I would recommend you use prototype.
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.
Can I put similar methods in an associative aray like this?
var function_hold = {
function1: function(){}
function2: function (){}
};
If not,
How do I group similar methods?
Similarly as you would with any other object-oriented programming language, you group functionality in objects. This works in JavaScript as well.
Your code actually creates an object. Alternatively you can use JavaScript's prototype mechanism.
var Person = function(firstname, surname){
this.firstname = firstname;
this.surname = surname;
}
Person.prototype.getFullName = function(){
return this.firstname + " " + this.surname;
}
You then call it like
var tom = new Person("Tom", "Jackwood");
tom.getFullName();
Yes thats possible and works fine.
Best Practice syntax would be the Module Pattern
var outerNamespace = {};
(function(ns) {
// ns is the local name of the object
ns.function1 = function() {}
ns.function2 = function() {}
//self executing anonymous function
} (outerNamespace));
Yeah, that should would just fine.
Yes, that will work fine. You can call the functions with function_hold.function1().
Note that normally you'll want to associate data with the functions as well:
var function_hold = {
x: 0,
function1: function(){
this.x++;
}
function2: function(){
alert(this.x);
}
};
I have some simple OO code I've written that I'm playing with:
//define a constructor function
function person(name, sex) {
this.name = name;
this.sex = sex;
}
//now define some instance methods
person.prototype.returnName = function() {
alert(this.name);
}
person.prototype.returnSex = function() {
return this.sex;
}
person.prototype.talk = function(sentence) {
return this.name + ' says ' + sentence;
}
//another constructor
function worker(name, sex, job, skills) {
this.name = name;
this.sex = sex;
this.job = job;
this.skills = skills;
}
//now for some inheritance - inherit only the reusable methods in the person prototype
//Use a temporary constructor to stop any child overwriting the parent prototype
var f = function() {};
f.prototype = person.prototype;
worker.prototype = new f();
worker.prototype.constructor = worker;
var person = new person('james', 'male');
person.returnName();
var hrTeamMember = new worker('kate', 'female', 'human resources', 'talking');
hrTeamMember.returnName();
alert(hrTeamMember.talk('I like to take a lot'));
Now this is all well and good. But I'm confused. I want to include namespacing as part of my code writing practice. How can I namespace the above code. As it is now I have 2 functions defined in the global namespace.
The only way I can think to do this is to switch to object literal syntax. But then how do I implement the pseudo-classical style above with object literals.
You could for example do following:
var YourObject;
if (!YourObject) {
YourObject = {};
YourObject.Person = function(name, sex) {
// ...
}
YourObject.Person.prototype.returnName = function() {
// ...
}
// ...
}
You don't have to use object literals, at least, not exclusively.
Decide on the single global symbol you'd like to use.
Do all your declaration work in an anonymous function, and explicitly attach "public" methods as desired to your global object:
(function(global) {
// all that stuff
global.elduderino = {};
global.elduderino.person = person;
global.elduderino.worker = worker;
})(this);
I may not be completely understanding the nuances of your issue here, but the point I'm trying to make is that Javascript makes it possible for you to start with your symbols being "hidden" as locals in a function, but they can be selectively "exported" in various ways.