Javascript redefine y anula el cuerpo de la función existente
Me pregunto si podemos cambiar el cuerpo de la función una vez que está construido.
var O = function(someValue){
this.hello = function(){
return "hello, " + someValue;
}
}
O.prototype.hello = function(){
return "hhhhhhh";
}
var i = new O("chris");
i.hello(); // -> this still returns the old definition "hello, chris"
La sentencia javascriptO.prototype.hello = function(){....}
no anula y redefine el comportamiento de la función de saludo. Porqué es eso ? Sé que tendrá un error de tipo si intentas reutilizar el parámetrosomeValue
.
// this will fail since it can't find the parameter 'someValue'
O.prototype.hello = function(){
return "aloha, " + someValue;
}
Me pregunto por qué permite agregar funciones durante el tiempo de ejecución como
O.prototype.newFunction = function(){
return "this is a new function";
}
i.newFunction(); // print 'this is a new function' with no problem.
pero no te permite cambiar la definición una vez que está definida. Hice algo mal ? ¿Cómo anulamos y redefinimos una función dentro de una clase? y ¿hay una manera de reutilizar el parámetro que pasamos anteriormente para crear el objeto? En estos casos, ¿cómo reutilizamos?someValue
Si queremos extenderle más funciones a ella.