I am wondering can we still change the function body once it is constructed ?
var O = function(someValue){
this.hello = function(){
If I recall correctly, functions that are direct members of objects take precedence over like-named members of that object's prototype. Therefore, O.prototype.hello
is usurped by O.hello
, even though the former is defined later in the code.
The reason someValue
isn't available to your O.prototype.hello
is because the scope of someValue
is constrained to the constructor function and any functions defined or executed within it. Since O.prototype.hello
is defined outside the scope of the O
constructor, it doesn't know about someValue
This is because when you access a property of an Object, JavaScript check the properties of the objects first, before going into its prototype.
This is analogous to Java's derived class overriding the base class functionality.
For a better understanding check the code example in Inheriting properties
Also note that someValue in your case is local to the constructor function. If you need it in other functions, you should assign it to this.someValue inside the constructor.
You'll be able to override the hello function for a particular Object here like the following. But not for the entire Class.
i.hello = function(){ console.log('even here someValue is not accessible');};
var O = function(someValue){
this.someValue = someValue;
this.hello = function(){
return "hello, " + someValue;
}
}
var i = new O("chris");
console.log(i.hello()); // prints hello, chris
i.hello = function() {
return 'Hi there '+ this.someValue;
}
console.log(i.hello()); // prints Hi there chris
var test = new O('Sujay')
console.log(test.hello()) // this still prints hello, Sujay
Note that here we have not changed the constructor, and hence this will not work with other instances like test
in the above example.
The best way to do it would be to define functions only in the prototype & not in the constructor, like the following snippet.
var O = function(someValue){
this.someValue = someValue;
};
O.prototype.hello = function(){
return "hello, " + this.someValue;
};
var i = new O("chris");
console.log(i.hello()); // prints hello, chris
O.prototype.hello = function() {
return 'Hi there '+ this.someValue;
}
console.log(i.hello()); // prints Hi there chris
var test = new O('Sujay')
console.log(test.hello()) // prints Hi there Sujay