gpt4 book ai didi

javascript - 如何创建一个可以影响任何值类型的方法?

转载 作者:行者123 更新时间:2023-12-02 23:51:01 24 4
gpt4 key购买 nike

警告:创建 native 对象和/或属性的扩展被认为是不好的形式,并且必然会导致问题。如果您不单独使用它,或者您不知道如何正确使用它,请不要使用它

<小时/>

我知道你可以使用ObjectStringNumberBoolean等来定义方法,像这样:

String.prototype.myFunction = function(){return this;} //only works on strings.

但是我需要能够做的是在任何值上使用它,并访问函数中的值。

我在谷歌上搜索了here ,但找不到合适的。

2/18/15 编辑:如果我使用 Object.prototype,是否有任何解决方法可以使其成为任何对象的属性?
每个请求,这里是用于 isString()

的当前函数
function isString(ins) {
return typeof ins === "string";
}

根据一些答案,我提出了一些代码以及由此引起的错误。

Object.prototype.isString = function() {
return typeof this === "string";
}
"5".isString() //returns false
"".isString() //returns false
var str = "string"
str.isString() //returns false

最佳答案

“点运算符函数”称为方法。在 JavaScript 中创建可用于任何数据类型的方法的最简洁方法是创建包装器。例如:

var Wrapper = defclass({
constructor: function (value) {
this.value = value;
},
isString: function () {
return typeof this.value === "string";
},
describe: function () {
if (this.isString()) {
alert('"' + this.value + '" is a string.');
} else {
alert(this.value + " is not a string.");
}
}
});

var n = new Wrapper(Math.PI);
var s = new Wrapper("Hello World!");

n.describe(); // 3.141592653589793 is not a string.
s.describe(); // "Hello World!" is a string.

function defclass(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}

通过创建自己的包装构造函数,您可以确保:

  1. 您的代码不会与其他人的代码混淆。
  2. 其他人的代码不会干扰您的代码。
  3. 您可以保持全局范围和原生原型(prototype)的干净。

几个流行的 JavaScript 库,例如 underscorelodash为此目的创建包装构造函数。

关于javascript - 如何创建一个可以影响任何值类型的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28574376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com