function Point(x, y){
this.x = x;
this.y = y;
}
const pointParent = {
add(point) {
return new Point(this.x + point.x, this.y + point.y);
}
};
const pointParentParent = {
sub(point) {
return new Point(this.x + point.x, this.y + point.y);
}
};
Object.setPrototypeOf(pointParent, pointParentParent);
Point.prototype = pointParent;
var p1 = new Point(10, 10);
var p2 = new Point(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
const point = (x, y) => {
return {
x:x,
y:y
}
}
const pointParent = {
add(pointc) {
return Object.setPrototypeOf(point(this.x + pointc.x, this.y + pointc.y), pointParent);
}
};
const pointParentParent = {
sub(pointc) {
return Object.setPrototypeOf(point(this.x + pointc.x, this.y + pointc.y), pointParent);
}
};
Object.setPrototypeOf(pointParent, pointParentParent);
var p1 = Object.setPrototypeOf(point(10,10), pointParent);
var p2 = Object.setPrototypeOf(point(10,-10), pointParent);
var sum = p1.add(p2);
var dif = p1.sub(p2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Function Prototype | |
Object Literal |
Test name | Executions per second |
---|---|
Function Prototype | 457756.2 Ops/sec |
Object Literal | 270245.9 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare two approaches to inheritance in JavaScript:
{ x: 10, y: 20 }
, and combines them using methods like add()
or sub()
.Options Compared
The benchmark compares the execution performance of these two approaches on a specific test case:
add()
) and subtraction (sub()
) operations on this inherited object.Pros and Cons of Each Approach
Prototype-based Inheritance (Function Prototype)
Pros:
Cons:
Object Literal-based Inheritance (Object Literal)
Pros:
Cons:
add()
or sub()
.Library Usage
In the benchmark code, two libraries are used:
Object.setPrototypeOf()
: This function sets the prototype of an object to another object, which is used in both approaches.Array.prototype.forEach()
and Math.pow()
might be used implicitly.Special JavaScript Features or Syntax
The benchmark uses some advanced JavaScript features:
Function.prototype.toString()
: The toString()
method of the Point
function is not explicitly shown, but it's implied that this method is used to generate a string representation of the object.Object.setPrototypeOf()
and function () { ... }
(anonymous functions) might be considered advanced topics.Alternative Approaches
Other approaches to inheritance in JavaScript could include:
class Point { ... }
) with inheritance using the extends
keyword.import * as Point from './Point.js';
) and inheritance through composition or prototypal inheritance.Keep in mind that each approach has its trade-offs, and the choice of which one to use depends on the specific requirements and constraints of your project.