I'm starting to use prototypes in Javascript with the help of the Mozilla Developer Network.
My problem is that I have 2 types: Field, and TextField, which inherits Field.
I want to create an Object from TextField and call an inherited method writeForm. Here's the code :
/**
* abstract type .
* Sets a parameter of the funcard associated with the html field. name => value
*/
function Field(){
console.log('create Field');
this.name = null;
this.value = null;
};
Field.prototype = {
/**
* Write the html Field in the field of the same name .
* This function must be overridden in each new type of Field.
*/
writeForm: function(){
// Function overloading
console.log('writeForm');
}
};
/**
* type text input
*/
function TextField(){
Field.call(this);
console.log('create TextField');
};
TextField.prototype = Object.create(Field.prototype, {
//Override
writeForm: function(){
Field.prototype.writeForm.apply(this, arguments);
// Function overloading
console.log('writeForm TextField');
}
});
var myfield = Object.create(TextField);
myfield.writeForm();
But the last line gives me an Uncaught TypeError: myfield.writeForm is not a function. I don't really understand why it can't find my method.
Could you help me?
Thanks!
1 Answer 1
First off, you're going to want to instantiate instances of TextField using either of these:
Object.create(TextField.prototype);
new TextField();
I'd suggest using new TextField() since you've defined a constructor.
Next, the second parameter to Object.create takes a set of property descriptors, which are different from just assigning properties directly to an object. To get an idea of how property descriptors work, check out Object.defineProperties. Instead, you'll want to assign your functions directly to the prototype after creating an instance of Field.prototype.
TextField.prototype = Object.create(Field.prototype);
TextField.prototype.writeForm = function() {
Field.prototype.writeForm.apply(this, arguments);
// Fonction à surcharger
console.log('writeForm TextField');
};
2 Comments
TextField.prototype.myFunction= function(){/*...*/} for each method of my prototypes, that's right ? It seems to work :) Thanks !
Object.create(TextField.prototype)ornew TextFieldsince you're using a constructor.var myfield = new TextField();