【发布时间】:2023-03-18 04:00:01
【问题描述】:
有人知道如何在原型属性下获取 typeof 对象吗?即我有下一个代码:
Object.prototype.someproperty = function(){
...do something...
console.log(typeof this);
..more...
}
在我的代码中,这总是“函数”,因为对象的构造函数是一个函数。当我这样打电话时
Array.someproperty(); //In this i want get "array"
//or
String.someproperty(); //In this i want get "string"
我想得到“数组”而不是“函数”……有人知道怎么做吗?
【问题讨论】:
-
typeof [] 将始终返回“object”,因为所有数组都是对象(在 JavaScript 中)。检查数组的更好方法是 --
Object.prototype.toString.call(yourVariableHere) === '[object Array]' -
我已经用这样的简单“名称”解决了我的问题。 Object.prototype.myfn= function(){ return this.name; } String.myfn(); //返回“字符串” Array.myfn(); //返回“数组” Function.myfn(); //返回“函数” Object.myfn(); //返回“对象” Number.myfn(); //return "Number" 我把 "someproperty" 改成 "myfn" 受到争议。谢谢大家。
-
呃,再一次,您只是将
myfn应用于函数!如果这是您的意图,您应该扩展Function.prototype而不是Object.prototype。这有非常真实的原因。此外,如果您需要完整的浏览器支持,函数上的.name是非标准属性,在某些浏览器中不起作用。
标签: javascript object typeof prototype-programming