l**********n 发帖数: 8443 | |
c*****n 发帖数: 173 | 2 如果是检查primitive type, 用typeof, 否则用instanceof。
如果是你自己的class/object, 在class当中加上classNamAnnotation property. 比如
var Animal = function(){
this.className = 'animal';
}
var dog = new Animal();
console.log(dog.className);
这样做比instanceof 更快。
【在 l**********n 的大作中提到】 : 有没有更好的?
|
l**********n 发帖数: 8443 | 3 不错
【在 c*****n 的大作中提到】 : 如果是检查primitive type, 用typeof, 否则用instanceof。 : 如果是你自己的class/object, 在class当中加上classNamAnnotation property. 比如 : var Animal = function(){ : this.className = 'animal'; : } : var dog = new Animal(); : console.log(dog.className); : 这样做比instanceof 更快。
|
n*****t 发帖数: 22014 | 4 可以用 underscore 判断类型,那个比较严谨,另一个办法是 constructor.name。
【在 l**********n 的大作中提到】 : 有没有更好的?
|
b***e 发帖数: 1419 | 5 There are two problems with your approach:
1. You need to maintain the name space to be unique for each class. This
does not scale in big projects.
2. You don't handle subclass. For instance,
var dog = new Dog();
dog.instanceof(Animal); // true
dog.instanceof(Dog); // true
To resolve 1, you can simply use the class object itself rather than a name
as the unique identifier of the class.
To resolve 2, you can define a instanceof function yourself and keep
overriding it in subclasses.
【在 c*****n 的大作中提到】 : 如果是检查primitive type, 用typeof, 否则用instanceof。 : 如果是你自己的class/object, 在class当中加上classNamAnnotation property. 比如 : var Animal = function(){ : this.className = 'animal'; : } : var dog = new Animal(); : console.log(dog.className); : 这样做比instanceof 更快。
|
c*****n 发帖数: 173 | 6 他原文没有提subclass。如果有的话自然也有一个名字。非得用instanceof的话就要这
么做
Dog.prototype.constructor = Dog;
用classnameannotation而不是用instanceof的原因是performance. 比较字符串比比较
prototype chain的constructor的内存地址快很多。至于是否有重名,那就多加注意,
多加前缀。同时用requirejs,不要把所有的东西都变成global. 我们的project 有上
千个class, 没有遇到过冲突。
name
【在 b***e 的大作中提到】 : There are two problems with your approach: : 1. You need to maintain the name space to be unique for each class. This : does not scale in big projects. : 2. You don't handle subclass. For instance, : var dog = new Dog(); : dog.instanceof(Animal); // true : dog.instanceof(Dog); // true : To resolve 1, you can simply use the class object itself rather than a name : as the unique identifier of the class. : To resolve 2, you can define a instanceof function yourself and keep
|
j**********3 发帖数: 3211 | 7 为什么会broken?。。。我咋就没broken呢 |
z******e 发帖数: 53 | |