JavaScript 如何向String类添加方法
在本文中,任务是在JavaScript中向String类添加方法。有两种方法,下面会详细介绍并附有示例:
添加方法到String类的两种方法
- 使用Object.defineProperty()方法
- 使用String.prototype.propertyName方法
方法1:使用Object.defineProperty()方法
Object.defineProperty() 方法用于直接定义一个新属性到对象或修改一个已有属性。它接受三个参数,第一个是对象,第二个是属性名称,最后一个是属性描述。在本示例中,返回字符串长度之和。
语法:
Object.defineProperties(obj, props)
示例: 此示例使用上述解释的方法。
// Input string
let str1 = "GeeksforGeeks";
let str2 = "A Computer Science Portal";
// Display input string
console.log(str1);
console.log(str2);
// Define custom method
Object.defineProperty(String.prototype, "SumOfLength", {
value: function (param) {
return this.length + param.length;
},
});
// Run custom method
function GFG_Fun() {
// Apply custom method
let res = str1.SumOfLength(str2);
// Display output
console.log("Total length: " + res);
}
// Funcion call
GFG_Fun();
输出
GeeksforGeeks
A Computer Science Portal
Total length: 38
方法2:使用String.prototype.propertyName方法
String.prototype.propertyName被用于向String类添加一个新方法。定义一个方法,接受对象传递的参数并执行所需的操作。在本例中,返回字符串长度的总和。
语法:
object.prototype.name = value
示例: 该示例使用上述解释的方法。
// Input string
let str1 = "JavaScript";
let str2 = "A Scripting Language for Web";
// Display input string
console.log(str1);
console.log(str2);
// Define custom method
String.prototype.SumOfLength = function (arg) {
return this.length + arg.length;
};
// Run custom method
function GFG_Fun() {
// Apply custom method
let res = str1.SumOfLength(str2);
// Display output
console.log("Total length: " + res);
}
// Funcion call
GFG_Fun();
输出
JavaScript
A Scripting Language for Web
Total length: 38