I am new to OOJS and I'm a little confused trying to understand inheritance, I created two simple classes, person and student that inherit from person, is there an option to create student by passing data in the parent's constructor? if it's possible, how to do it ? can a child get all the properties and methods from the parent or only the methods?
**the fname and lName in the alert are undefined
function Person(fNme, lName) {
this.fname = fNme;
this.lName = lName;
}
Object.prototype.go = function() {
alert("I am going now last time you see "+ this.lName);
}
function Student() {
this.study = function () {
alert("I am studing !");
}
}
Student.prototype = new Person();
var s1 = new Student("sam", "bubu");
alert(s1.fname +"+"+ s1.lName)
you can use constructor stealing.
function Student(fName,lName) {
Person.call(this,fName,lName);
this.study = function () {
alert("I am studing !");
}
}
when you call Student constructor you can pass along arguments to Person() with call() to initialize variables in Person
This is done by just calling the parent constructor
function Student(fName, lName, whateverelse) {
Person.call( this, fName, lName ); // call base class constructor function
this.study = function () {
alert("I am studing !");
}
}
Related
can someone explain what's the difference between this:
<script>
function Employee() {
this.name = "serj";
}
function Manager() {
Employee.call(this);
this.dept = "general";
}
var jim = new Manager;
console.log(jim.name); //serj
</script>
And this:
<script>
function Employee() {
this.name = "serj";
}
Manager.prototype = Object.create(Employee.prototype);
function Manager() {
Employee.call(this);
this.dept = "general";
}
var jim = new Manager;
console.log(jim.name); //serj
</script>
So the question is why should I create a prototype?If manager calls employee and all works fine?
Calling the constructor function for Employee will run all the code that is inside that function. It won't perform all the side effects (i.e. creating a new object, assigning it to this and making it an instance of Employee … and you wouldn't want it to because you want it to be an instance of Manager).
I have the following two files:
product.js ,
define(function(products) {
return {
reserveProduct: function(id) {
console.log(id);
}
}
});
purchase.js
define(["products"], function(products) {
return {
function(id) {
products.reserveProduct(id);
}
}
})
I am creating a purchase object.
new purchase(1);
Now I want to extend purchase.js as AnalyExtendpurchase.js and create a new object as
new AnalyExtendpurchase(1);
I want to pass id as parameter to parent object i.e to purchase object
Normally in Java the equivalent code would be:
Purchase.java
public class Purchase{
purchase(int id){
this.id=id;
}
}
AnalyExtendpurchase.java
AnalyExtendpurchase extends purchase{
AnalyExtendpurchase(int id){
super(id);
}
}
Object creation in java
new AnalyExtendpurchase(10);
I want to follow same object creation pattern using requirejs.
I have provided a sample example below : Hope it can help you ..
Let's say we have ABC() constructor like:
function ABC(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
Then Let's define XYZ() constructor function,
function XYZ(firstName, lastName,subject) {
ABC.call(this, firstName, lastName);
this.subject = subject;
}
Here call() is used to call a function defined somewhere else, but in the current context
Finally you can set XYZ() prototype as :
XYZ.prototype = Object.create(ABC.prototype);
XYZ.prototype.constructor = XYZ;
Here, above line create a new object and make it the value of XYZ.prototype and will inherit from ABC.prototype
Hope the above prototypal inheritance sample helps you . happy coding :)
I've a code
function person() {
name = "David";
hello = function() {
console.log("I'm in hello");
};
}
And I want to invoke hello function from outside. How can I achieve it?
Assign hello (and name) to this in person:
function Person() {
this.name = "David";
this.hello = function() {
console.log("I'm in hello");
};
};
Then, you can access the function like this:
var p = new Person();
p.hello();
this assigns the variables to the Person. This prevents the variables from polluting the global scope.
You could also pass parameters to Person:
function Person(name) {
this.name = name;
this.hello = function() {
alert("Hello! I'm " + this.name + '!');
};
};
var p = new Person("Fred");
p.hello();
function person() {
this.name = "David";
this.hello = function() {
console.log("I'm in hello");
};
}
var personObj = new person();
personObj.hello ();
What you can do is that:
function person() {
name = "David";
this.hello = function() {
console.log("I'm in hello");
};
}
var johnny = new person();
johnny.hello();
See this nice article: http://www.phpied.com/3-ways-to-define-a-javascript-class/
function person() {
name = "David";
this.hello = function() {
console.log("I'm in hello");
};
}
var p = new person();
p.hello();
or
function person() {
var obj={};
obj.name = "David";
obj.hello = function() {
console.log("I'm in hello");
};
return obj;
}
var p = person();
p.hello();
This is for your curiosity and clarity :)
You have declared global variables inside a function. Untill you execute the function the global variables will not come into existence and would not be accessible. Once you call the function the globals would be defined and initialized properly and thereafter you can call them from any scope in the javascript.
function person() {
name = "David";
hello = function() {
console.log("I'm in hello");
};
}
Now, in order to call hello from outside without using this or class pattern, you will have to first make a call (method execution) to person method. see this:
either person(); or console.log(person()); but not console.log(person);
and then you can easily call hello();
NOTE: This is for David's understanding purpose. Please do not use
arbitrarily global variables in your javascript.
I am getting following error
Unable to get property 'showMsg' of undefined or null reference
on the last line of below code:
Function.prototype.showMsg = function () {
alert("This is a sample message.");
};
function Person() {
this.name = "Mahesh";
};
var personObj = new Person();
personObj.prototype.showMsg();
Actually I should be able to access showMsg() from Person instance since I have added it to the Function.prototype. Then why I am getting this error?
Well You Understand it all Wrong
Function.prototype.showMsg = function () {
alert("This is a sample message.");
};
function Person() {
this.name = "Mahesh";
};
var personObj = new Person();
personObj.prototype.showMsg();
First you prototyped the function class, then create a custom class called Person, then you create an instance of Person. And then you are calling the very blue print which is showMsg which is 2 Mistakes 1 showMsg is not Bounded into the Person and then to call it if its bounded you call it directly like this
personObj.showMsg()
Will To Make This Script Work from my point of View if i got you write
write it like this ->
function Person() {
this.name = "Mahesh";
};
Person.prototype.showMsg = function () {
alert("This is a sample message.");
};
var personObj = new Person();
personObj.showMsg();
my script bound the showMsg Directly to the Person Class if you need it through the Person Object and Through The Function Class To Then you have to inherit from Function Class Like This
Function.prototype.showMsg=function () {
alert("This is a sample message.");
};
function Person() {
this.name = "Mahesh";
};
Person.prototype = Function;
Person.prototype.constructor = Person;
var personObj = new Person();
personObj.showMsg();
Regards
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling base method using JavaScript prototype
I want to inheritance object that will override function in javascript.
From the method I want to call to the base method.
In this case I inherit object reader from Person and now I want to override the function getName meaning that in reader first I want to call the function on Person and then to do some changes.
<script>
/* Class Person. */
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
var reader = new Person('John Smith');
reader.getName = function() {
// call to base function of Person, is it possible?
return('Hello reader');
}
alert(reader.getName());
</script>
Vincent answered your direct question but here is what you would do if you would like to set up a true inheritance hierarchy where you can further extend Reader.
Create your person class:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function(){
alert('Person getName called for ' + this.name);
return this.name;
}
Create a Reader class as well:
function Reader(name) {
// Calls the person constructor with `this` as its context
Person.call(this, name);
}
// Make our prototype from Person.prototype so we inherit Person's methods
Reader.prototype = Object.create(Person.prototype);
// Override Persons's getName
Reader.prototype.getName = function() {
alert('READER getName called for ' + this.name);
// Call the original version of getName that we overrode.
Person.prototype.getName.call(this);
return 'Something';
}
Reader.prototype.constructor = Reader;
And now we can repeat a similar process to extend Reader with say a VoraciousReader:
function VoraciousReader(name) {
// Call the Reader constructor which will then call the Person constructor
Reader.call(this, name);
}
// Inherit Reader's methods (which will also inherit Person's methods)
VoraciousReader.prototype = Object.create(Reader.prototype);
VoraciousReader.prototype.constructor = VoraciousReader;
// define our own methods for VoraciousReader
//VoraciousReader.prototype.someMethod = ... etc.
fiddle:
http://jsfiddle.net/7BJNA/1/
Object.create: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create
Object.create(arg) is creating a new object whose prototype is what was passed in as an argument.
Edit
Its been years since this original answer and now Javascript supports the class keyword which works as you'd expect if you're coming from language like Java or C++. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
Since you are correctly overriding the function on the object itself and not on its prototype, you can still call the prototype function with your object.
reader.getName = function() {
var baseName = Person.prototype.getName.call(this);
...
}
I use this technique from John Resig to get inheritance and method overriding. It even lets you access to the overridden method by calling this._super().
http://ejohn.org/blog/simple-javascript-inheritance/
This is one way to do it:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
}
var reader = new Person('John Smith');
reader.oldGetName = reader.getName;
reader.getName = function() {
//call to base function of Person , is it possible ?
return this.oldGetName();
}
alert(reader.getName());
http://jsfiddle.net/fXWfh/