Is it possible to redefine a JavaScript class's method?

Asked
Active3 hr before
Viewed126 times

9 Answers

methodpossiblejavascript
90%

is it possible to redefine the class's method later?,When using a constructor function in JavaScript to create a class, is it possible to redefine the class's method later?, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , Meta Stack Overflow

Yes. However, you must not assign the new function to a property of the Person constructor, but to the instance itself:

var p2 = new Person("Sue");
p2.sayHello(); // Hello, Sue
p2.sayHello = function() {
   alert('Hola, ' + this.name);
};
p2.sayHello(); // Hola, Sue

If you want to do this for all new instances automatically (and have not used the prototype for the method, which you easily could exchange as in @dystroy's answer), you will need to decorate the constructor:

Person = (function(original) {
   function Person() {
      original.apply(this, arguments); // apply constructor
      this.sayHello = function() { // overwrite method
         alert('Hola, ' + this.name);
      };
   }
   Person.prototype = original.prototype; // reset prototype
   Person.prototype.constructor = Person; // fix constructor property
   return Person;
})(Person);
load more v
88%

Class syntax allows to specify not just a class, but any expression after extends.,As we can recall from the chapter Native prototypes, JavaScript itself uses prototypal inheritance for built-in objects. E.g. Date.prototype.[[Prototype]] is Object.prototype. That’s why dates have access to generic object methods.,The syntax to extend another class is: class Child extends Parent.,As rabbits are animals, Rabbit class should be based on Animal, have access to animal methods, so that rabbits can do what “generic” animals can do.

class Animal {
   constructor(name) {
      this.speed = 0;
      this.name = name;
   }
   run(speed) {
      this.speed = speed;
      alert(`${this.name} runs with speed ${this.speed}.`);
   }
   stop() {
      this.speed = 0;
      alert(`${this.name} stands still.`);
   }
}

let animal = new Animal("My animal");
load more v
72%

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.,If there is a constructor present in the subclass, it needs to first call super() before using "this".,The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructor.,Note: Class expressions are subject to the same hoisting restrictions as described in the Class declarations section.

class Rectangle {
   constructor(height, width) {
      this.height = height;
      this.width = width;
   }
}
load more v
65%

JavaScript uses prototypal inheritance: every object inherits properties and methods from its prototype object.,The traditional class as the blueprint to create objects, used in languages like Java or Swift, does not exist in JavaScript. The prototypal inheritance deals only with objects.,I must say that the class syntax in JavaScript does a great job to abstract from the prototypal inheritance. To describe the class syntax I haven’t even used the term prototype.,The prototypal inheritance can emulate the classic class inheritance. To bring the traditional classes to JavaScript, ES2015 standard introduces the class syntax: a syntactic sugar over the prototypal inheritance.

The special keyword class defines a class in JavaScript:

javascriptclass User { // The body of class}
load more v
75%

I noticed something strange though. I am very new to JS yet. why is ‘function’ keyword not allowed/ not needed in a JS class? I am curious. Please shed some light?, bhagya | june 19, 2021 I noticed something strange though. I am very new to JS yet. why is ‘function’ keyword not allowed/ not needed in a JS class? I am curious. Please shed some light? Reply michael krasnov | june 25, 2021 It’s just the way syntax was decided, no particular reason Reply ,Because the React team tells you not to. While they did not explicitly deprecate the class-based components yet, they are likely to in the near future.,the car.prototype returns the start function, that the JS engine executes immediately.

Pre-ES6 classes

Even though the class keyword was added to JavaScript since ES6 (ECMAScript 2015), people were using classes earlier. The way to achieve this was constructor functions and prototype delegation. To show you exactly what I mean, I am going to implement the same class in ES5 and ES6 environments. Consider a class Car and SportsCar that inherits Car. Both of them have make and model properties and start method, but SportsCar also has the turbocharged property and overrides the start method:

Car

Pre-ES6 classes

Even though the class keyword was added to JavaScript since ES6 (ECMAScript 2015), people were using classes earlier. The way to achieve this was constructor functions and prototype delegation. To show you exactly what I mean, I am going to implement the same class in ES5 and ES6 environments. Consider a class Car and SportsCar that inherits Car. Both of them have make and model properties and start method, but SportsCar also has the turbocharged property and overrides the start method:

SportsCar

Pre-ES6 classes

Even though the class keyword was added to JavaScript since ES6 (ECMAScript 2015), people were using classes earlier. The way to achieve this was constructor functions and prototype delegation. To show you exactly what I mean, I am going to implement the same class in ES5 and ES6 environments. Consider a class Car and SportsCar that inherits Car. Both of them have make and model properties and start method, but SportsCar also has the turbocharged property and overrides the start method:

Car

Pre-ES6 classes

Even though the class keyword was added to JavaScript since ES6 (ECMAScript 2015), people were using classes earlier. The way to achieve this was constructor functions and prototype delegation. To show you exactly what I mean, I am going to implement the same class in ES5 and ES6 environments. Consider a class Car and SportsCar that inherits Car. Both of them have make and model properties and start method, but SportsCar also has the turbocharged property and overrides the start method:

make

Pre-ES6 classes

Even though the class keyword was added to JavaScript since ES6 (ECMAScript 2015), people were using classes earlier. The way to achieve this was constructor functions and prototype delegation. To show you exactly what I mean, I am going to implement the same class in ES5 and ES6 environments. Consider a class Car and SportsCar that inherits Car. Both of them have make and model properties and start method, but SportsCar also has the turbocharged property and overrides the start method:

model

Pre-ES6 classes

Even though the class keyword was added to JavaScript since ES6 (ECMAScript 2015), people were using classes earlier. The way to achieve this was constructor functions and prototype delegation. To show you exactly what I mean, I am going to implement the same class in ES5 and ES6 environments. Consider a class Car and SportsCar that inherits Car. Both of them have make and model properties and start method, but SportsCar also has the turbocharged property and overrides the start method:

start

Pre-ES6 classes

Even though the class keyword was added to JavaScript since ES6 (ECMAScript 2015), people were using classes earlier. The way to achieve this was constructor functions and prototype delegation. To show you exactly what I mean, I am going to implement the same class in ES5 and ES6 environments. Consider a class Car and SportsCar that inherits Car. Both of them have make and model properties and start method, but SportsCar also has the turbocharged property and overrides the start method:

SportsCar

Pre-ES6 classes

Even though the class keyword was added to JavaScript since ES6 (ECMAScript 2015), people were using classes earlier. The way to achieve this was constructor functions and prototype delegation. To show you exactly what I mean, I am going to implement the same class in ES5 and ES6 environments. Consider a class Car and SportsCar that inherits Car. Both of them have make and model properties and start method, but SportsCar also has the turbocharged property and overrides the start method:

turbocharged

Pre-ES6 classes

Even though the class keyword was added to JavaScript since ES6 (ECMAScript 2015), people were using classes earlier. The way to achieve this was constructor functions and prototype delegation. To show you exactly what I mean, I am going to implement the same class in ES5 and ES6 environments. Consider a class Car and SportsCar that inherits Car. Both of them have make and model properties and start method, but SportsCar also has the turbocharged property and overrides the start method:

start
load more v
40%

JavaScript’s prototype system can be interpreted as a somewhat informal take on an object-oriented concept called classes. A class defines the shape of a type of object—what methods and properties it has. Such an object is called an instance of the class.,Remember that methods that exist on plain objects come from Object.prototype.,A property like speak(line) in an object expression is a shorthand way of defining a method. It creates a property called speak and gives it a function as its value.,Can you think of a way to call hasOwnProperty on an object that has its own property by that name?

Methods are nothing more than properties that hold function values. This is a simple method:

let rabbit = {};
rabbit.speak = function(line) {
   console.log(`The rabbit says '${line}'`);
};

rabbit.speak("I'm alive.");
// → The rabbit says 'I'm alive.'
load more v
22%

So, where can we change the value of the $name property? There are two ways:,Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.,2. Outside the class (by directly changing the property value):,When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

Define a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:

class
load more v
60%

Example #8 Calling an anonymous function stored in a property,Example #3 Creating an instance, That means that calling an anonymous function which has been assigned to a property is not directly possible. Instead the property has to be assigned to a variable first, for instance. It is possible to call such a property directly by enclosing it in parentheses. , It is possible to access a member of a newly created object in a single expression:

$this is defined(A)

Deprecated: Non - static method A::foo() should not be called statically in % s on line 27
$this is not defined.

Deprecated: Non - static method A::foo() should not be called statically in % s on line 20
$this is not defined.

Deprecated: Non - static method B::bar() should not be called statically in % s on line 32

Deprecated: Non - static method A::foo() should not be called statically in % s on line 20
$this is not defined.
load more v
48%

For us to be able to make objects like this from a specific class, that class has to contain a constructor method - or shortly, a constructor. A constructor is practically speaking a manual on how to instantiate an object and assign values. The most common practice for creating a constructor is to name it the same as the class, but it doesn't have to be.,Then, when instantiating this class, we'd pass in some arguments to the constructor, invoking a new object:,For instance, in the constructor from before, we've used the passed variables passedName and passedFounder, but what if these were just name and founder which make more sense?,We've created an object of the BasketballPlayer class which contains the attributes used in the Athlete class, as well as two new attributes, sport and teamName - specific for the BasketballPlayer class.

For example, for our ProgrammingLanguage class, we'd define a ProgrammingLanguage() constructor that defines how we assign values to the attributes within the class, when instantiating it. It typically accepts 0..n arguments used as values for the attributes:

class ProgrammingLanguage {
   // Attributes
   String name;
   String founder;

   // Constructor method
   ProgrammingLanguage(string passedName, string passedFounder) {
      name = passedName;
      founder = passedFounder;
   }
}
load more v

Other "method-possible" queries related to "Is it possible to redefine a JavaScript class's method?"