我想知道以下情况是否可能。我正在尝试编写一个对象工厂,它将构造不同类型的对象。我想弄清楚的是,是否可以在java脚本中将类型设置为函数或对象之外的其他类型?与 C# 中的类似,Car 的类实例是 typeof Car,即使基本类型是 object。希望我能清楚地解释这一点。解释它的最佳方式如下所示:
var object = function(){
switch(id){
case 1:
$_objInstance = new Car();
break;
case 2:
$_objInstance = new Animal();
break;
return $_objInstance;
}
function Car(){
this.Name = "GM";
}
document.write(object instanceof Car);
or
typof(
object) == Car //is this possible?
提前致谢!快乐编码:)
最佳答案
What I am trying to figure out, is if it is possible in java script to set the type as something other then a function or object?
不,你不能。但是:
JavaScript 确实有一个
instanceof
运算符,您可以使用它来测试实例以查看它是否可能是由给定构造函数构造的:if (obj instanceof Car) { // ... }
Function#name
在野外仍然不可靠(因为 JavaScript 引擎尚未可靠地设置它),但您可以在构造函数上显式设置它:Car.name = "Car";
...然后使用 obj.constructor.name 查找构造函数的名称。这依赖于对象正确继承 constructor
属性,如果您不弄乱函数的 prototype
属性上的默认对象,它就会正确继承。
几年前我wrote a blog post关于 typeof
、instanceof
、Object.prototype.toString
以及可用来确定某物是什么的各种其他方法,尽管我没有提及仅设置您自己的名字的选项。
这是使用 .constructor.name
的示例:
function Car() {
}
Car.name = "Car";
function Animal() {
}
Animal.name = "Animal";
console.log("Randomly constructing 10 Cars or Animals:");
for (var n = 0; n < 10; ++n) {
var x = Math.random() < 0.5 ? new Car() : new Animal();
console.log("We got: " + x.constructor.name);
}
当我上面说
That relies on the object inheriting the
constructor
property correctly, which it will if you don't mess up the default object on the function'sprototype
property.
让我给你举一个困惑的例子,这样你就知道要注意什么。您经常看到人们这样做:
// PROBLEMATIC: Wipes out the `constructor` property
function Car() {
}
Car.prototype = {
drive: function() {
}
// ...
};
也就是说,它们不是增强 Car.prototype 最初获得的对象,而是替换它。出于各种原因,我更喜欢增强(例如,不要替换整个对象,只需向其添加属性),但如果您替换它,您可以确保您为新的构造函数提供了正确的构造函数
:
// Keeps `constructor` correct
function Car() {
}
Car.prototype = {
constructor: Car,
drive: function() {
}
// ...
};
关于javascript - 您可以将对象类型设置为自定义名称而不是 Javascript 中的函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35044123/