Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何获取JavaScript对象';什么课?_Javascript_Oop - Fatal编程技术网

如何获取JavaScript对象';什么课?

如何获取JavaScript对象';什么课?,javascript,oop,Javascript,Oop,我创建了一个JavaScript对象,但是如何确定该对象的类呢 我想要类似于Java的.getClass()方法的东西 JavaScript中没有与Java完全对应的语言。这主要是因为JavaScript是一种语言,而Java是一种语言 根据您需要的内容,JavaScript中有几个选项: obj. func.,proto 举几个例子: function Foo() {} var foo = new Foo(); typeof Foo; // == "funct

我创建了一个JavaScript对象,但是如何确定该对象的类呢


我想要类似于Java的
.getClass()
方法的东西

JavaScript中没有与Java完全对应的语言。这主要是因为JavaScript是一种语言,而Java是一种语言

根据您需要的内容,JavaScript中有几个选项:

  • obj.
  • func.
    proto
举几个例子:

function Foo() {}
var foo = new Foo();

typeof Foo;             // == "function"
typeof foo;             // == "object"

foo instanceof Foo;     // == true
foo.constructor.name;   // == "Foo"
Foo.name                // == "Foo"    

Foo.prototype.isPrototypeOf(foo);   // == true

Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21);            // == 42

注意:如果您使用Uglify编译代码,它将更改非全局类名称。为了防止这种情况,Uglify有一个参数,您可以在使用或时将其设置为false。

Javascript是一种无类语言:没有任何类像Java中那样静态定义类的行为。JavaScript使用原型而不是类来定义对象属性,包括方法和继承。可以使用JavaScript原型模拟许多基于类的功能。

您可以通过以下方法获得对创建对象的构造函数的引用:

如果需要在运行时确认对象的类型,可以使用运算符:

obj instanceof MyObject // true

在javascript中,没有类,但我认为您需要构造函数名称,而
obj.constructor.toString()
将告诉您需要什么。

此getNativeClass()函数返回
“undefined”
表示未定义的值,返回
“null”
表示空值。
对于所有其他值,
CLASSNAME
-部分是从
[object CLASSNAME]
中提取的,这是使用
object.prototype.toString.call(value)
的结果

getAnyClass()
的行为与getNativeClass()相同,但也支持自定义构造函数

函数getNativeClass(obj){ 如果(对象类型==“未定义”)返回“未定义”; 如果(obj==null)返回“null”; 返回Object.prototype.toString.call(obj.match(/^\[Object\s(.*)\]$/)[1]; } 函数getAnyClass(obj){ 如果(对象类型==“未定义”)返回“未定义”; 如果(obj==null)返回“null”; 返回obj.constructor.name; } getClass(“”==“字符串”; getClass(true)=“布尔”; getClass(0)=“数字”; getClass([])===“数组”; getClass({})==“对象”; getClass(null)==“null”; getAnyClass(新的(函数Foo(){}))==“Foo”; getAnyClass(新类Foo{})==“Foo”; //等等。。。 在现代浏览器中是一种可靠的方法
Function.name
正式添加到ES6中的标准中,使其成为一种符合标准的方式,将JavaScript对象的“类”作为字符串获取。如果使用
var obj=new MyClass()
实例化该对象,它将返回“MyClass”

它将为数字返回“Number”,为数组返回“Array”,为函数返回“Function”,等等。它的行为通常与预期的一样。只有在没有原型的情况下,通过
object.create(null)
创建对象,或者通过匿名定义(未命名)函数实例化对象时,才会失败

还要注意的是,如果要缩小代码,与硬编码类型字符串进行比较是不安全的。例如,不检查是否
obj.constructor.name==“MyType”
,而是检查
obj.constructor.name==MyType.name
。或者只是比较构造函数本身,但是这不会跨DOM边界工作,因为每个DOM上都有不同的构造函数实例,因此对它们的构造函数进行对象比较不会工作。

要获得“伪类”,可以通过

obj.constructor
假设在执行继承时正确设置了
构造函数--

Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
这两条线,加上:

var woofie = new Dog()
将使
woofie.constructor
指向
Dog
。请注意,
Dog
是一个构造函数,是一个
函数
对象。但是如果(woofie.constructor==Dog){…}
,您可以执行

如果希望将类名作为字符串获取,我发现以下方法很有效:

它获取构造函数,将其转换为字符串,并提取构造函数的名称


请注意,
obj.constructor.name
本可以很好地工作,但它不是标准的。它在Chrome和Firefox上,但不在IE上,包括IE9或IE10RTM。

我在IE中找到
object.constructor.toString()
返回
[objectobjectclass]
,而不是在chome中返回的
函数objectClass(){}
。因此,我认为中的代码在IE中可能无法正常工作。我对代码进行了如下修复:

代码:

同意DFA,这就是为什么当没有命名类发现

时,我认为原型是类的原因。 以下是Eli Grey发布的升级功能,以符合我的想法

function what(obj){
    if(typeof(obj)==="undefined")return "undefined";
    if(obj===null)return "Null";
    var res = Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
    if(res==="Object"){
        res = obj.constructor.name;
        if(typeof(res)!='string' || res.length==0){
            if(obj instanceof jQuery)return "jQuery";// jQuery build stranges Objects
            if(obj instanceof Array)return "Array";// Array prototype is very sneaky
            return "Object";
        }
    }
    return res;
}
下面是
getClass()
getInstance()
您可以使用
this.constructor
获取对象类的引用

从实例上下文: 从静态上下文:
对于ES6中的Javascript类,可以使用
object.constructor
。在下面的示例类中,
getClass()
方法返回您期望的ES6类:

var Cat = class {

    meow() {

        console.log("meow!");

    }

    getClass() {

        return this.constructor;

    }

}

var fluffy = new Cat();

...

var AlsoCat = fluffy.getClass();
var ruffles = new AlsoCat();

ruffles.meow();    // "meow!"

如果从
getClass
方法实例化类,请确保将其括在括号中,例如
ruffles=new(fluffy.getClass())(args

为了保持其完整的向后兼容性记录ECMAScript 6,JavaScript仍然没有
类型(尽管不是每个人都理解这一点)。它确实有一个
class
关键字作为创建原型的
class
语法的一部分,但是仍然没有所谓的class。JavaScript现在不是,而且从来都不是经典的OOP语言。从类的角度讲JS是o
function getObjectClass(obj) {
    if (obj && obj.constructor && obj.constructor.toString) {
        var arr = obj.constructor.toString().match(
            /function\s*(\w+)/);

        if (arr && arr.length == 2) {
            return arr[1];
        }
    }

    return undefined;
}
var getObjectClass = function (obj) {
        if (obj && obj.constructor && obj.constructor.toString()) {
            
                /*
                 *  for browsers which have name property in the constructor
                 *  of the object,such as chrome 
                 */
                if(obj.constructor.name) {
                    return obj.constructor.name;
                }
                var str = obj.constructor.toString();
                /*
                 * executed if the return of object.constructor.toString() is 
                 * "[object objectClass]"
                 */
                 
                if(str.charAt(0) == '[')
                {
                        var arr = str.match(/\[\w+\s*(\w+)\]/);
                } else {
                        /*
                         * executed if the return of object.constructor.toString() is 
                         * "function objectClass () {}"
                         * for IE Firefox
                         */
                        var arr = str.match(/function\s*(\w+)/);
                }
                if (arr && arr.length == 2) {
                            return arr[1];
                        }
          }
          return undefined; 
    };
    
function what(obj){
    if(typeof(obj)==="undefined")return "undefined";
    if(obj===null)return "Null";
    var res = Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
    if(res==="Object"){
        res = obj.constructor.name;
        if(typeof(res)!='string' || res.length==0){
            if(obj instanceof jQuery)return "jQuery";// jQuery build stranges Objects
            if(obj instanceof Array)return "Array";// Array prototype is very sneaky
            return "Object";
        }
    }
    return res;
}
function A() {
  this.getClass = function() {
    return this.constructor;
  }

  this.getNewInstance = function() {
    return new this.constructor;
  }
}

var a = new A();
console.log(a.getClass());  //  function A { // etc... }

// you can even:
var b = new (a.getClass());
console.log(b instanceof A); // true
var c = a.getNewInstance();
console.log(c instanceof A); // true
function A() {};

A.getClass = function() {
  return this;
}

A.getInstance() {
  return new this;
}
var Cat = class {

    meow() {

        console.log("meow!");

    }

    getClass() {

        return this.constructor;

    }

}

var fluffy = new Cat();

...

var AlsoCat = fluffy.getClass();
var ruffles = new AlsoCat();

ruffles.meow();    // "meow!"
class Foo {
  get foo () {
    console.info(this.constructor, this.constructor.name)
    return 'foo'
  }
}

class Bar extends Foo {
  get foo () {
    console.info('[THIS]', this.constructor, this.constructor.name, Object.getOwnPropertyNames(this.constructor.prototype))
    console.info('[SUPER]', super.constructor, super.constructor.name, Object.getOwnPropertyNames(super.constructor.prototype))

    return `${super.foo} + bar`
  }
}

const bar = new Bar()
console.dir(bar.foo)
> $ babel-node ./foo.js                                                                                                                   ⬡ 6.2.0 [±master ●]
[THIS] [Function: Bar] 'Bar' [ 'constructor', 'foo' ]
[SUPER] [Function: Foo] 'Foo' [ 'constructor', 'foo' ]
[Function: Bar] 'Bar'
'foo + bar'
var arr = new Array('red', 'green', 'blue');
var arr2 = new Array('white', 'black', 'orange');
Object.defineProperty(arr,'last', {
  get: function(){
    return this[this.length -1];
  }
});
console.log(arr.last) // blue
Object.defineProperty(Array.prototype,'last', {
  get: function(){
    return this[this.length -1];
  }
});
console.log(arr.last) // blue
console.log(arr2.last) // orange
Object.defineProperty(arr.__proto__,'last2', {
  get: function(){
    return this[this.length -1];
  }
});
console.log(arr.last) // blue
console.log(arr2.last) // orange
class Test {
  // your class definition
}

nameByType = function(type){
  return type.prototype["constructor"]["name"];
};

console.log(nameByType(Test));
console.log(Test.prototype.constructor.name); // returns "Test" 
Object.defineProperty(Object.prototype, "getClass", {
    value: function() {
      return this.constructor.name;
    }
});

var x = new DOMParser();
console.log(x.getClass()); // `DOMParser'

var y = new Error("");
console.log(y.getClass()); // `Error'
 class A{ 
   constructor(name){ 
     this.name = name
   }
 };

 const a1 = new A('hello a1');
const a2 = new (Object.getPrototypeOf(a1)).constructor('hello from a2')
// the analog of const a2 = new A()

console.log(a2.name)//'hello from a2'
class Person {
  type = "developer";
}
let p = new Person();

p.constructor.name // Person
function getClass(obj) {

   // if the type is not an object return the type
   if((let type = typeof obj) !== 'object') return type; 
    
   //otherwise, access the class using obj.constructor.name
   else return obj.constructor.name;   
}
function getClass(obj) {

   // if the type is not an object return the type
   let type = typeof obj
   if((type !== 'object')) { 
      return type; 
   } else { //otherwise, access the class using obj.constructor.name
      return obj.constructor.name; 
   }   
}