Closure类框架中接口的实现

Closure类框架中接口的实现

本文介绍了测试对象是否是Google Closure类框架中接口的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Google Closure继承机制来测试JavaScript对象是否是接口的实现?

在通过new my.Dog()创建的对象中找不到my.Animal的任何提示,并且object instanceof my.Animal无法正常工作.关于接口的唯一信息是忘记在子类中实现方法时的编译器错误.

I could not find any hint of my.Animal in the objects created via new my.Dog() and object instanceof my.Animal didn't work. The only information about the interface are compiler errors when forgetting to implement methods in the child class.

/**
 * @interface
 */
my.Animal = function() {};

/**
 * Does something.
 * @return {string}
 */
my.Animal.prototype.doSomething;

/**
 * @constructor
 * @implements {my.Animal}
 */
my.Dog = function() {};

/** @inheritDoc */
my.Dog.prototype.doSomething() = function {
    return "something";
}

var dog = new my.Dog();
console.log(dog instanceof my.Animal); // returns false

我发现的一种方法是大致测试接口的属性,尽管这在很多方面都是不好的:

One way I found is to approximately test for the property of the interfaces, though that's bad in so many aspects:

console.log(!!dog.doSomething); // returns true

推荐答案

@interface纯粹是类型检查器构造.在未编译的代码中,没有任何东西可以检查@interface/@implements的注释以添加任何连线以进行运行时检查.闭包的目的是使代码在编译之前和之后都运行相同(假设您遵守所使用的优化模式的限制).需要进行运行时检查时,典型的模式是标记实现您感兴趣的接口的类:

@interface is purely a type checker construct. In uncompiled code there is nothing that can inspect the comments for @interface/@implements to add any wiring for runtime checks. The goal for Closure is that the code will run the same before and after compilation (assuming that you observe the restriction for the optimization mode you are using). The typical pattern when a runtime check is desired is to tag class that implements the interface you are interested in:

my.Dog.prototype.implements_my_Animal = true;

然后

if (foo.implements_my_Animal) ...

这有点烦人,所以您在不需要的地方看不到它.包装此包装的方法有多种,但是,如果使用ADVANCED模式,则大多数方法都会导致实现类(在示例中为my.Dog)转义,如果未使用,则无法将其删除.

This is a bit annoying so you don't see it where it isn't needed. There are various ways to wrap this but, if you use ADVANCED mode, most result in the implementing class (my.Dog in your example) escaping and not being removable if unused.

这篇关于测试对象是否是Google Closure类框架中接口的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:48