Inherit function in javascript - javascript

I have a function that is similar to each other. How can I make declaring a function easier without duplicating
function constructor (name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
// create a Penguin constructor here
function Penguin(name, numLegs){
this.name=name;
this.numLegs = numLegs;
}
// create a sayName method for Penguins here
Penguin.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
// our test code
var theCaptain = new Penguin("Captain Cook", 2);
theCaptain.sayName();

You were almost there.
// create a Penguin constructor here
function Penguin(name, numLegs){
Animal.call(this, name, numLegs);
};
// Reuse the prototype chain
Penguin.prototype = Object.create(Animal.prototype);
Penguin.prototype.constructor = Penguin;

Related

The equivalent to using __proto__?

I'm trying to use the revealing module pattern with inheritance. I seem to have it working fine, but it uses "__proto__", which I understand it's considered deprecated. Is there a better was to create the inheritance with out using "__proto__"?
var Person = (function() {
var _name;
var api = {
init: init,
getName: getName
}
return api;
function init(name) {
_name = name;
}
function getName() {
return _name;
}
}())
var Teacher = (function() {
var _subject = "Math";
var api = {
getSubject: getSubject,
say: say
}
api.__proto__ = Person;
return api;
function getSubject() {
return _subject;
}
function say() {
console.log("I am " + this.getName() + " and I teach " + _subject)
}
}());
Teacher.init("Bob");
Teacher.say() // I am Bob and I teach math
https://plnkr.co/edit/XbGx38oCyvRn79xnn2FR?p=preview
The direct equivalent – setting the prototype, still a bad idea – is Object.setPrototypeOf:
Object.setPrototypeOf(api, Person);
The normal way of creating an object based on a prototype with Object.create and then adding properties to it works fine here, though:
var api = Object.create(Person);
api.getSubject = getSubject;
api.say = say;
but ideally you would just use constructors:
class Person {
constructor(name) {
this._name = name;
}
getName() {
return this._name;
}
}
class Teacher extends Person {
constructor(name) {
super(name);
this._subject = 'Math';
}
getSubject() {
return this._subject;
}
say() {
console.log(`I am ${this.getName()} and I teach ${this.getSubject()}`);
}
}
var teacher = new Teacher('Bob');
teacher.say() // I am Bob and I teach math
without ES6:
function Person(name) {
this._name = name;
}
Person.prototype.getName = function () {
return this._name;
};
function Teacher(name) {
Person.call(this, name);
this._subject = 'Math';
}
Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.getSubject = function () {
return this._subject;
};
Teacher.prototype.say = function () {
console.log('I am ' + this.getName() + ' and I teach ' + this.getSubject());
};
var teacher = new Teacher('Bob');
teacher.say(); // I am Bob and I teach math

javascript prototyping, what am i doing wrong here

http://jsfiddle.net/johnm01/c5k0yevm/
im trying to understand prototyping again but not sure what im doing wrong here, why is undefined output when the method screamName is called?
function Person1(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.sayName = function sayMyName() {
alert(this.name + this.age + this.sex);
}
};
var p1 = new Person1("tim", 56, "male");
p1.sayName();
Person1.prototype.screamName = function screamName(name) {
this.name = name;
alert(this.name);
};
p1.screamName();
The screamName function expects a name argument which you're not supplying, and subsequently are assigning to this.name. Thus, it is undefined. I believe you intended to write this:
Person1.prototype.screamName = function screamName() {
alert(this.name);
};
Well, it looks like you've defined your method to take in a parameter of "name", but you haven't actually passed any parameter into the method when you call it. I also think that you need to create a new Person1 object in order to have a Person1 object with the screamname method.
function Person1(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.sayName = function sayMyName() {
alert(this.name + this.age + this.sex);
}
}
var p1 = new Person1("tim", 56, "male");
p1.sayName();
Person1.prototype.screamName = function screamName() {
alert(this.name);
};
var p2 = new Person1("bob", 22, "male");
p2.screamName();
https://jsfiddle.net/johnm01/c5k0yevm/

In OPP JS can you access a method declared inside a prototype function from the constructor?

I'm reading about OPP js and while going over an example and was wondering if in:
function Person(name){
this.name = name;
}
Person.prototype.sayName = function(){
var tempName = this.name;
var saySomething = function(){
console.log(tempName);
}
//return saySomething();
}
var person1 = new Person('chris');
is theres a way to fire the saySomething method from the constructor.
eg.
person1.sayName().saySomething() //which doesnt work obviously
Returning an object when sayName will work:
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
var tempName = this.name;
return {
saySomething: function() {
console.log(tempName);
}
};
};
var person1 = new Person('chris');
person1.sayName().saySomething(); // logs 'chris'

How do I create a class in javascript

I need a student class in javascript with 2 data members Name and Age and 2 method get_record() and set_record(name,age). How do I do it in javascript and create multiple object of that class.
var Student = function(age, name){
this.age = age;
this.name = name;
this.get_age = function(){
return this.age;
}
this.get_name = function(){
return this.name;
}
this.set_age = function(age){
this.age = age;
}
this.set_name = function(name){
this.name = name;
}
}
var student = new Student(20,"XYZ");
You can model classes with new JavaScript based languages. Dart and TypeScript are probably the most popular in this respect.
This example is based on the JavaScript output from a TypeScript class.
var Student = (function() {
function Student(name, age) {
this.name = name;
this.age = age;
}
Student.prototype.get_record = function() {
return "Name: " + this.name + "\nAge: " + this.age;
}
Student.prototype.set_record = function(name, age) {
this.name = name;
this.age = age;
}
return Student;
})();
// Usage
var a = new Student("John", 23);
var b = new Student("Joe", 12);
var c = new Student("Joan", 44);
function student (age,name) {
this.name = name;
this.age = age;
this.get_record = function() {
return "name:"+this.name+" , age:"+this.age;
}
this.set_record = function(_name,_age) {
this.name=_name;
this.age=_age;
}
}
You can use 'constructor function'.
function Student() {
this.get_record = function(){ return this.name; };
this.set_record = function(name, age) {
this.name = name;
this.age = age;
};
return this;
}
var student1 = new Student();
var student2 = new Student();
student1.set_record('Mike', 30);
student2.set_record('Jane', 30);
student1.get_record();
student2.get_record();
More complex class structures are constructed via prototypes

javascript private variable through inheritance

I'm stuck with a problem using javascript...
I want to declare a private variable in a class that can't be used from its sublclass...what I've tried is:
function Person(){
var _name
this.setName = function(name){
_name = name
}
this.getName = function(){
return _name
}
}
function GreetingPerson(){
var self = this;
self.sayHello = function(){
console.log(self.getName() + ': "Hello!"');
}
}
GreetingPerson.prototype = new Person()
GreetingPerson.prototype.contructor = GreetingPerson;
var manuel = new GreetingPerson()
manuel.setName('Manuel');
manuel.sayHello();
var world = new GreetingPerson()
world.setName('World');
world.sayHello();
manuel.sayHello();
console.log(manuel.name)
In this way the name variable is private, but it is also static, so the last wo sayHello method calls, will write the same output.
I've tried also changing the Person class in this way:
function Person(){
this.setName = function(name){
this.name = name
}
this.getName = function(){
return this.name
}
}
But in this way it is not longer private.
What is the correct way to achieve it?
EDIT: Using something like #teddybeard says, you can get it too:
function Person(){
var _name;
this.setName = function(name){
_name = name;
};
this.getName = function(){
return _name;
};
return this;
}
function GreetingPerson(){
Person.call(this);
this.sayHello = function(){
console.log(this.getName() + ': "Hello!"');
};
return this;
}
GreetingPerson.prototype = new Person();
GreetingPerson.prototype.constructor = GreetingPerson;
var manuel = new GreetingPerson();
manuel.setName('Manuel');
manuel.sayHello();
var world = new GreetingPerson();
world.setName('World');
world.sayHello();
manuel.sayHello();
console.log(manuel._name);
But I'm not pretty sure if this is actually ok. The problem is that if you don't do something like Person.call(this); inside the constructor of GreetingPerson, you will not create a new instance of Person and it will always use the same _name value.
Check out Eloquent Javascript if you have time. I think this code should work for your purposes of inheritance.
function Person() {
var _name
this.setName = function(name) {
_name = name
}
this.getName = function() {
return _name
}
}
function GreetingPerson() {
Person.call(this);
this.sayHello = function() {
console.log(this.getName() + ': "Hello!"');
}
}
// taken from Eloquent Javascript
function clone(object) {
function OneShotConstructor() {}
OneShotConstructor.prototype = object;
return new OneShotConstructor();
}
GreetingPerson.prototype = clone(Person.prototype);
GreetingPerson.prototype.contructor = GreetingPerson;
var manuel = new GreetingPerson()
manuel.setName('Manuel');
manuel.sayHello();
var world = new GreetingPerson()
world.setName('World');
world.sayHello();
manuel.sayHello();
console.log(manuel.name)​;​

Categories