In JavaScript, there is no built-in extend
function. However, you can achieve inheritance or extension using various techniques. Here are a few commonly used approaches:
1. Prototype Inheritance:
function Parent(name) {
this.name = name;
}
Parent.prototype.greet = function() {
console.log('Hello, ' + this.name);
};
function Child(name) {
Parent.call(this, name);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.sayGoodbye = function() {
console.log('Goodbye, ' + this.name);
};
var child = new Child('Alice');
child.greet(); // Output: Hello, Alice
child.sayGoodbye(); // Output: Goodbye, Alice
2. Class Inheritance (ES6):
class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log('Hello, ' + this.name);
}
}
class Child extends Parent {
constructor(name) {
super(name);
}
sayGoodbye() {
console.log('Goodbye, ' + this.name);
}
}
let child = new Child('Alice');
child.greet(); // Output: Hello, Alice
child.sayGoodbye(); // Output: Goodbye, Alice
3. Object.assign:
var parent = {
name: '',
greet: function() {
console.log('Hello, ' + this.name);
}
};
var child = Object.create(parent);
child.name = 'Alice';
child.sayGoodbye = function() {
console.log('Goodbye, ' + this.name);
};
child.greet(); // Output: Hello, Alice
child.sayGoodbye(); // Output: Goodbye, Alice
The approach you choose depends on your specific requirements and the version of JavaScript you are using.
JavaScript extend function
Simple example code of creating a custom extend
function in JavaScript, you can define a function that copies properties from one object to another.
function extend(target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
var parent = {
name: 'John',
age: 30,
greet: function() {
console.log('Hello, my name is ' + this.name + ' and I am ' + this.age + ' years old.');
}
};
var child = {
name: 'Alice',
hobby: 'Painting'
};
extend(child, parent);
child.greet();
console.log(child.hobby);
Output:
Keep in mind that this extend
function performs a shallow copy, meaning that nested objects or arrays are not deeply copied. If you need a deep copy or more advanced features, you might consider using libraries like lodash
or Object.assign()
.
Do comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version