有没有 JavaScript 相当于 Java 的 class.getName() ?
最佳答案
Is there a JavaScript equivalent of Java's
class.getName()?
class Foo {} is Foo.name . thing的名称的类,不考虑 thing的类型,是 thing.constructor.name . ES2015 环境中的内置构造函数具有正确的 name属性(property);例如(2).constructor.name是 "Number" .Object.prototype.getName = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};
现在,您的所有对象都将具有函数 getName() ,它将以字符串形式返回构造函数的名称。我在 FF3 中对此进行了测试和 IE7 ,我不能说其他实现。constructor属性(property)...object它的 constructor 有一个值属性,但取决于如何object构造以及您想用该值做什么,它可能有用也可能没有用。constructor属性来测试对象的类型,如下所示:var myArray = [1,2,3];
(myArray.constructor == Array); // true
因此,这足以满足大多数需求。那说...function Thingy() {
}
Thingy.prototype = {
method1: function() {
},
method2: function() {
}
};
Objects通过 new Thingy 构建会有 constructor指向 Object 的属性,不是 Thingy .所以我们一开始就摔倒了;您根本无法信任 constructor在您无法控制的代码库中。function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a
事情现在不像你期望的那样工作:var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true
因此,如果 object,您可能会得到意想不到的结果。您的测试有不同的 object设为其 prototype .在本讨论的范围之外,还有一些方法可以解决这个问题。constructor 还有其他用途属性(property),其中一些很有趣,另一些则不那么有趣;现在我们不会深入研究这些用途,因为它与本次讨论无关。.constructor当你想检查来自不同的对象的类型时,类型检查会中断 window对象,比如 iframe 或弹出窗口。这是因为每种内核类型都有不同的版本 constructor在每个“窗口”中,即iframe.contentWindow.Array === Array // false
instanceof运算符(operator)...instanceof operator 是一种干净的测试方式 object类型也是如此,但有其自身的潜在问题,就像 constructor 一样属性(property)。var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true
但是instanceof无法用于文字值(因为文字不是 Objects )3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false
文字需要包裹在 Object 中为了 instanceof工作,例如new Number(3) instanceof Number // true
.constructor检查对文字工作正常,因为 .方法调用隐式地将文字包装在它们各自的对象类型中3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true
为什么 3 有两个点?因为 Javascript 将第一个点解释为小数点 ;)instanceof也不能跨不同窗口工作,原因与 constructor 相同。属性(property)检查。name constructor 的属性(property)属性(property)...constructor 来说很常见完全错误和无用。myObjectInstance.constructor.name会给你一个包含 constructor 名称的字符串使用的函数,但受有关 constructor 的警告的约束前面提到的属性。if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s+([^\s(]+)\s*\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1] : "";
},
set: function(value) {}
});
}
更新版本 从有问题的文章。这是在文章发表 3 个月后添加的,这是文章作者 Matthew Scharley 推荐使用的版本。此更改的灵感来自 comments pointing out potential pitfalls在之前的代码中。if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s([^(]{1,})\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1].trim() : "";
},
set: function(value) {}
});
}
Object.prototype.toString - toString 的低级和通用实现- 获取所有内置类型的类型Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]
可以编写一个简短的辅助函数,例如function type(obj){
return Object.prototype.toString.call(obj).slice(8, -1);
}
删除 cruft 并获得类型名称type('abc') // String
但是,它会返回 Object对于所有用户定义的类型。// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == "Foo"); // true
// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // false
(obj.constructor.name == "Foo"); // false
// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object); // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == ""); // true
// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == ""); // true
// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object); // true
(obj.constructor == Object); // true
(obj.constructor.name == "Object"); // true
虽然并非所有排列都出现在这组示例中,但希望有足够的排列可以让您了解根据您的需要,事情可能会变得多么困惑。不要假设任何事情,如果你不完全理解你所追求的,你可能最终会在你不期望的地方破坏代码,因为缺乏对微妙之处的理解。typeof运算符可能看起来是一个明显的遗漏,但它确实没有帮助识别 object 是否有用。是给定的类型,因为它非常简单。了解哪里typeof有用很重要,但我目前不认为它与本次讨论非常相关。不过,我愿意改变。 :)
关于javascript - 获取对象类型的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/332422/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url