Home > Article > Backend Development > How to call regular functions under js with code_PHP tutorial
The ECMAScript 4 proposal stated that this feature would be added to the ES4 specification, but later in the ES4-discuss mailing list discussion, this proposal may be abandoned.
However, you can implement these methods similarly by adding call and apply methods to RegExp.prototype. It not only helps in functional design, but also enables the implementation of duck-typed code that is valid for both functions and regular expressions. So let's add these methods.
RegExp.prototype.call = function (context, str) {
return this.exec(str);
};
RegExp.prototype.apply = function (context, args) {
return this.exec(args[0]);
}; Note that the above two methods completely ignore the context parameter. You can submit null or any other object as context, and you will get something similar Regular return value of exec method. Using the above method, it becomes much easier to use regular expressions and functions normally no matter what the situation. Some obvious examples, such as these are useful in array iteration in JavaScript 1.6. The following filter, every, some, and map methods can be executed across browsers.
if (!Array.prototype.filter) {
// Returns an array. If the provided filter function returns true, then returns the elements in the existing array.
Array.prototype.filter = function (func, context) {
var results = [];
for (var i = 0; i < this.length; i++) {
if ( i in this && func.call(context, this[i], i, this))
results.push(this[i]);
}
return results;
};
}
if (!Array.prototype.every) {
// Return true if each element in the array satisfies the provided test function.
Array.prototype.every = function (func, context) {
for (var i = 0; i < this.length; i++) {
if (i in this && !func.call( context, this[i], i, this))
return false;
return true;
return true;
if (!Array.prototype. some) {
// Returns true if at least one element in the array satisfies the provided test function.
Array.prototype.some = function (func, context) {
for (var i = 0; i < this.length; i++) {
if (i in this && func.call(context , this[i], i, this))
return true;
return false;
};
}
if (!Array.prototype.map ) {
// Returns an array. Each element in the existing array calls the return value of the provided function.
Array.prototype.map = Function (func, context) {
var results = [];
for (var I = 0; I & lt; this.length; i ++) {
if ( i in this)
results[i] = func.call(context, this[i], i, this);
}
return results;
};
} because of the exec method Returns an array or null value, with appropriate type conversions to true and false. The above code allows us to use it like this: ["a","b","ab","ba"].filter(/^a/ ), returns all values starting with "a": ["a","ab"].
Indeed, Array.prototype.filter has been implemented in Firefox, because the indirect call of exec already works in this browser. However, if the filter does not add the RegExp.prototype.call method, it cannot be executed across browsers.