I'm trying to do a function like .split() or .replace() or .remove(), i think is like a prototype function, how i can make this example works:
this.logThis = function(a) {
console.log("The " + this + "is cool like a " + a);
}
var food = "apple";
food.logThis("orange");Run Code Online (Sandbox Code Playgroud)
To get this Output:
> "The apple is cool like a orange"
Run Code Online (Sandbox Code Playgroud)
Important: I need the most short code possibly, pure javascript, NO JQUERY
If you want to be able to call the function on a string, you'll need to extend the String prototype:
String.prototype.logThis = function(a) {
console.log("The " + this + " is cool like a " + a);
}
var food = "apple";
food.logThis("orange");Run Code Online (Sandbox Code Playgroud)
This'll work, but you might want to alter it slightly to use a more modern JavaScript syntax:
String.prototype.logThis = function(a) {
console.log(`The ${this} is cool like a ${a}`);
}
const food = "apple";
food.logThis("orange")Run Code Online (Sandbox Code Playgroud)
It is also worth pointing out that extending native objects is considered by many to be a bad practice (here's why), so you might rather alter your function to avoid this.
Here's one way of doing that:
const obj = {
food: 'apple',
logThis(a) {
console.log(`The ${this.food} is cool like a ${a}`);
}
}
obj.logThis("orange");Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |