Creating a Class and calling on it's properties (javascript) - javascript

So the idea is to create a class Animal and the set properties to it as a new object
Here is what I have:
var name;
var type;
function Animal(name,type){
this.type = type,
this.name = name,
toString = function(){return this.name + "is a " + this.type;}
};
var cat = new Animal('Max','cat');
cat.type;
everytime I run it - I seem to fail at the toString part? Pretty new and trying to learn this - is there something I am missing?

You don't need to declare those top variables, the arguments should be local to the function. The syntax is wrong too, you should use semicolons, not commas, and toString becomes a global variable since you forgot to use var.
What you want is this.toString so this works inside and refers to the instance, or better yet, create a method on the prototype so it's re-usable for all instances of Animal:
function Animal(name,type) {
this.type = type;
this.name = name;
}
Animal.prototype.toString = function() {
return this.name + "is a " + this.type;
};

function Animal(name, type) {
this.type = type;
this.name = name;
};
Animal.prototype.toString = function() {
return this.name + "is a " + this.type;
}
var cat = new Animal('Max', 'cat');
console.log(cat); // Prints "Max is a cat"

Related

How to use constructors as a prototype chain?

Suppose that I have a javascript constructor:
function Person(name) {
this.name = name;
this.hello = function () { return "It's a-me, " + name + "!"; };
}
the Person "type" has a convenient method, hello that I would like to re-use on another type Student. I would like for a Student to have the following structure:
function Student(name) {
this.name = name;
this.hello = function () { return "It's a-me, " + name + "!"; };
this.books = [];
}
One option is to use the code for Student as-is above. This is sub-optimal for the usual reasons, such as that if I want it to mirror the Person type, then I have to manually keep their code in sync. Anyway, this is not good.
A second option (from this answer) is to do something like:
function Student(name) {
Person.call(this, name);
this.books = [];
}
When I mario = new Student("mario") I get the following:
Object { name: "mario", hello: hello(), books: [] }
I've successfully achieved the inheritance that I wanted, but this has the unfortunate property of placing all of the desired properties into my object. Notably, for example, there is a "hello" property on mario. It would be nice if that "hello" property could be looked up in the prototype chain.
How can I neatly create a prototype chain given the relevant object constructors?
When you create an object with new, the this value of your constructor function is set to the object, and that object's prototype is set to the prototype of the constructor Function being called.
That's why your properties are currently being added to the created object.
function Student {
this.name = name
}
const student = new Student('John')
// is (almost) equivalent to the following
const student = {}
student.name = 'John'
But if you want to add properties to the prototype instead, so that you can use inheritance, then in ES5 Javascript you can do so by assigning properties directly to the prototype of your constructor function.
function Person(name) {
this.name = name;
}
// Person is a function
// Its prototype is an instance of Object, and it has no properties
// i.e. something like Person.prototype = new Object()
Person.prototype.hello = function() {
return 'It is I, ' + this.name
}
// Now Person.prototype has one property, "hello", which is a function.
function Student(name) {
Person.call(this, name)
this.books = [];
}
// Student is a function
// Its prototype is also an instance of Object with no properties
// the following is the magic line
Student.prototype = Object.create(Person.prototype)
// We replace the prototype of the Student function with a new object, but
// Object.create() allows us to set the prototype to an existing object, in this case Person.prototype,
// Person.prototype is itself an instance of Object, and we previously
// added the "hello" function to it as a property.
const student = new Student('John')
// So what happens here?
// First a new object is created, and its prototype is set to Student.prototype
// Then we call Person.call(this)
// Which executes the body of the Person function
// So you get the properties on the object itself through the body of the Person and Student functions
// And you get the shared functionality through the prototype chain of instance -> Student.prototype -> Person.prototype -> Object.prototype
Hope that helps!
You can use prototyping method or class sugar method as you want.
Here is a simple example :
function Student(name) {
this.name = name;
this.books = [];
}
Student.prototype.hello = function(){
return "It's a-me, " + this.name + "!";
}
Student.prototype.addBook = function(book){
this.books.push(book);
}
Student.prototype.getBooks = function(){
return this.books;
}
let mario = new Student("Mario");
console.log(mario.hello());
mario.addBook("prototyping");
mario.addBook("chain");
console.log(mario.getBooks());
class Person {
constructor(name) {
this.name = name;
this.books = [];
}
hello(){
return "It's a-me, " + this.name + "!";
}
addBook(book){
this.books.push(book);
}
getBooks(){
return this.books;
}
}
let luigi = new Person("Luigi");
console.log(luigi.hello());
luigi.addBook("classSugar");
luigi.addBook("classType");
console.log(luigi.getBooks());
For longer chains use Object.assign, here is an example of making a GradStudent that is both a Student and a Person and has the personality of a Comedian and also has the properties and methods of a 4th class GameCharacter:
(function() {
//Person
function Person(name) {
this.name = name;
this.helloString = "Hello my name is "
}
Person.prototype.name = "Bob";
Person.prototype.hello = function() {
return this.helloString + this.name;
};
//Student
function Student(name, books) {
Person.call(this, name);
this.books = books;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.books = ["math","reading"];
//Comedian
function Comedian(name) {
Person.call(this,name);
};
Comedian.prototype = Object.create(Person.prototype);
Comedian.prototype.constructor = Comedian;
Comedian.prototype.hello = function() {
return "I don't know what my parents where thinking when they name me Squat, just kidding, my name is " + this.name;
};
//GameCharacter
function GameCharacter(power) {
this.power = power;
};
GameCharacter.prototype = new Object();
GameCharacter.prototype.constructor = GameCharacter;
GameCharacter.prototype.gainPower = function(power) {
this.power += ", "+power;
};
GameCharacter.prototype.statePower = function() {
return this.power;
};
//GradStudent
function GradStudent(name, books, degree) {
Comedian.call(this, name);
Student.call(this,name,books);
GameCharacter.call(this, "jumping");
this.degree = degree;
this.gainPower("flying");
}
GradStudent.prototype = Object.create(Student.prototype);
Object.assign(GradStudent.prototype, Comedian.prototype, GameCharacter.prototype);
GradStudent.prototype.constructor = GradStudent;
var gradStudent = new GradStudent("Bill",["C", "C++", "JavaScript"], "B.S.");
console.log(gradStudent.hello() + " I have a " + gradStudent.degree +" I am studying " + gradStudent.books.toString() + ". \n In a game I play my power's are "+ gradStudent.statePower() + ". \n Is gradStudent also a Student? " + (gradStudent instanceof Student) + "" );
var otherStudent = new Student("Jennifer" ,["english", "science"]);
console.log(gradStudent.books.toString() + " " + otherStudent.books.toString());
})();
GradStudent is an instance of Student, it's a type of Student, and can also do all the things Comedian and GameCharacter does. The value of Object.assign is that kind of multiple inheritance.
I can accomplish such a thing with the following:
function Student(name) {
Object.setPrototypeOf(this, new Person(name));
this.books = [];
}
However, I'm not familiar enough with javascript to know what possible problems might arise with this solution. Coming from other OO style languages, it feels weird for the prototype of mario to be an actual instance of a Person, but I suppose everything in js is an instance, in some sense, so this might just be bias on my part.

Javascript private variables and parameters have same name

function() {
var name;
this.set = function( name ) {
this.name = name; <-- this
}
}
How would I write the line so that I can assign the parameter to the private variable? Unlike Java, "this" also points to a function, so I can't figure it out.
You'll just have to use a different name for the argument so it won't shadow the private variable name outside the function set, that's all.
var SomeClass = function() {
var name;
this.set = function( otherName ) { // argument should have a diffirent name so it won't shadow the other variable "name"
name = otherName;
}
this.get = function() {
return name;
}
};
var ins = new SomeClass();
ins.set("Jim Carrey"); // OK
console.log(ins.get()); // OK
console.log(ins.name); // undefined as expected
Inside the function set, inner name variable will get more preference than the outer name variable. In order to assign some value to the outer variable, you will have to have a different name inside or outside.
However, You can do something like,
function() {
this.name = '';
this.set = function( name ) {
this.name = name; <-- this
}
}
This is not assigning the new value to the private variable, this is assigning the value to the object's property.
2020 edit:
I happen to come back to this question and realized that I was mistaken.
Better code example.
type = function() {
var name = "default";
var self = this;
this.set = function(name) {
console.log("this: " + this);
console.log("self: " + self);
console.log("name: " + name);
name = name; // <-- name shadowed
}
this.get = function() {
return name;
}
}
test = new type();
console.log("test.name: " + test.name);
console.log("test.get: " + test.get());
test.set("new")
console.log("test.name: " + test.name);
console.log("test.get: " + test.get());
I wanted to avoid name shadowing which can be done in Java by doing
this.name = name;
However, in Javascript, "name" is declared as a public property and initialized so that defeats the purpose of this thought-exercise.
"self" technique won't work either (this is where I mistakenly thought it would work)
The true answer is Aadit M Shah's comment in the first answer.
With the recent EcmaScript (or not so recent), Javascript lets you assign getter and setter to a property, so this technique is probably not needed.

Define getter / setter in object function

I'm learning JavaScript, and was wondering if it was possible to define getters and setters in object functions.
The main difference is the way of calling it, if defined as getFullName = function(), I should call the method as myObj.getFullName(), however, as for arrays, a getter allows for it to be called as a simple property myObj.fullName (without parenthesis).
As I saw in MDN reference (http://mzl.la/1CIUuIw), it is easily done in Object Literals:
var obj = {
get var(){
return "something";
}
}
However, I can't do it on object functions like so:
function obj(name, lname){
this.name = name;
this.lastName = lname;
get fullName(){
return this.name + " " + this.lastName;
}
}
Getting a "Unexpected identifier" error...
As get XX(){} is used for var obj = {}; But here you use a constructor to create new object. So you should use MDN - Object.defineProperty().
And if you want the fullName apply on all object create from obj, apply it on its prototype.
function obj(name, lname){
this.name = name;
this.lastName = lname;
}
Object.defineProperty(obj.prototype, 'fullName', {
get : function() {
return this.name + " " + this.lastName;
}
});
var aObj = new obj("first", 'lastN');
console.log(aObj.fullName);
UPDATE:
If you want a more straight way, and not scared to try new things, then ES2015's class notation can do it more easily:
// ES2015 - class
class obj {
constructor(name, lname) {
this.name = name;
this.lname = lname;
}
// Define getter method for fullName
get fullName() {
return this.name + " " + this.lastName;
}
}
var aObj = new obj('Billy', 'Hallow');
console.log(aObj.fullName);
Currently most browsers don't support that, if you want to use this in your site, you need to use js compilers like Babel to transpile it from ES2015 to ES5.
Babel also provide a playground for those who has interest in ES2015, you can copy above codes to the playground to see how it works.
Javascript uses prototype inheritance and its functions start with function keyword. By convention, object's first character is capitalised.
function Obj(name, lname){
this.name = name;
this.lastName = lname;
}
Obj.prototype.get = function() {
return this.name + " " + this.lastName;
}
var person = new Obj('luke', 'lim');
console.log(person.get()); // 'luke lim'
Just make a variable and assign the function to it.
function obj(name, lname){
this.name = name;
this.lastName = lname;
this.fullName = function(){
return this.name + " " + this.lastName;
};
}
Try to read something about Javascript closure if you want to know more about it.
Furthermore, this link, Javascript methods, is explaining EXACTLY what you need, which is adding a method to an object. And a getter is traditionally just a method.
function obj(name, lname){
this.name = name;
this.lastName = lname;
}
obj.prototype.getfullName = function(){
return this.name + " " + this.lastName;
}
use this as
a = new obj("My","Name");
a.getfullName() //"My Name"

Get the public properties of a class without creating an instance of it?

Let's imagine that we have a JavaScript class:
var Person = (function () {
function Person(name, surname) {
this.name = name;
this.surname = surname;
}
Person.prototype.saySomething = function (something) {
return this.name + " " + this.surname + " says: " + something;
};
return Person;
})();
I want to iterate its methods and properties. I have no problem with the methods.
var proto = Person.prototype,
methods = Object.keys(proto);
// iterate class methods ["saySomething"]
for (var i = 0; i < methods.length; i++) {
// do something...
}
My problem comes when I want to iterate its properties:
var proto = Person.prototype,
targetInstance = new Person(), // this is my problem!
properties = Object.getOwnPropertyNames(targetInstance),
// iterate class properties ["name", "surname"]
for (var i = 0; i < properties.length; i++) {
// do something...
}
The only way that I have found is to create an instance and use Object.getOwnPropertyNames. I want to use this code as part of a framework so I will not have control over the classes defined by other developers. I want to avoid the need of creating an instance because if the constructor had some sort of validation like:
function Person(name, surname) {
if(typeof name === "undefined" || typeof surname === "undefined"){
throw new Error()
}
this.name = name;
this.surname = surname;
}
I wouldn't be able to use the code above. Do you know if it is possible to get the public properties of a class without creating an instance of it?
The properties don't exist until an object constructs them.
If your class looked like:
var Person = (function () {
Person.prototype.name = null;
Person.prototype.surname = null;
function Person(name, surname) {
this.name = name;
this.surname = surname;
}
Person.prototype.saySomething = function (something) {
return this.name + " " + this.surname + " says: " + something;
};
return Person;
})();
you would see name and surname too, but of course you can't count on the objects looking like that.
Do you know if it is possible to get the public properties of a class without creating an instance of it?
If you are talking about runtime them no, not without ugly hacks like toString (which gives you a string representation of the function body).
However you can get these at compile time using the TypeScript language service and then do code generation to assist the runtime (https://github.com/Microsoft/TypeScript/wiki/Using-the-Language-Service-API).
Neither of these are trivial.

a prototype question in javascript

<script type="text/javascript">
var Person =
{
Create: function(name, age) {
this.name = name;
this.age = age;
},
showMe: function() {
return " Person Name: " + this.name + " Age: " + this.age + " ";
}
};
function New(aClass, aParams) {
function new_() {
aClass.Create.apply(this, aParams);
};
new_.prototype = aClass;
var obj = new new_();
return obj;
}
</script>
I don't quite understand the code above. Could someone tell me the meanings of Person, Create, showMe, New and new_? Thanks a lot.
Person is an object with two functions - Create and showMe. In JavaScript, there are no classes, only objects, and this is how you write up an object - using 'Object Literal Notation' (the curly braces and functions/properties separated by commas).
New is a clever re-implementation of the new keyword. Instead of classes, javascript has prototypes, and instead of creating an instance of a class you create a copy of the prototype. In this case, if you passed Person to New(), it would used as the prototype in new_.prototype = aClass, and the rest of this function will return an object with the Person prototype, which means any changes to Person later on will be inherited into obj as well (unless obj has overridden them).
`Person` -- a variable w/ 'parts' (used loosely) `Person.Create` and `Person.showMe'
`Person.Create` -- function of `Person` that sets `Person.name` and `Person.age` to its arguments
`Person.showMe` -- returns a string explaining values of `Person.name` and `Person.age`
`New` -- a function intended to instantiate new Person's thru prototypal (this is NOT class based) inheritenced
`New._new` -- `New` uses this to get it done
Basically thru prototype inheritence, even though Person is only 'made' once, other 'versions' of it can be constructed in kind. It can be used like this (try it here: http://jsfiddle.net/PBhCs/)
var Person = {
Create: function(name, age)
{
this.name = name;
this.age = age
},
showMe: function()
{
return " Person Name: " + this.name + " Age: " + this.age + " ";
}
};
function New(aClass, aParams)
{
function new_()
{
aClass.Create.apply(this, aParams);
};
new_.prototype = aClass;
var obj = new new_();
return obj;
}
var a = New(Person, ['moo', 5]);
var b = New(Person, ['arf', 10]);
alert(a.showMe() + b.showMe());

Categories

Resources