我正在尝试为模仿Crockford的 Javascript 类开发一个简单的寄生接口,我想实现一些基本的内省方法。给定下面的类,我该如何编写正确识别对象类的方法class_name
?is_a
function Parent(name) {
var self = {};
self.name = name;
self.init = function() {
console.debug('init', self);
return self;
};
self.ama = function() {
return "AMA Parent named " + self.name;
};
// Introspective methods
self.class_name = function() {
// returns class name as a string
};
self.is_a = function(obj_class) {
// returns boolean indicating whether object is instance of obj_class
};
self = self.init();
return self;
}
function Child(name) {
var self = new Parent(name);
var base_ama = self.ama;
self.ama = function() {
var ama = base_ama();
return ama + ". NOT!";
};
self.init();
return self;
}
以下是预计将通过的测试:
var alice = new Parent('Alice');
assert_equal(alice.name, 'Alice');
assert_equal(alice.class_name(), 'Parent');
assert(alice.is_a(Parent));
assert_not(alice.is_a(Child));
assert_equal(alice.ama(), 'AMA Parent named Alice');
var bob = new Child('Bob');
assert_equal(bob.class_name(), 'Child');
assert_not(bob.is_a(Parent));
assert(bob.is_a(Child));
assert_equal(bob.ama(), 'AMA Parent named Bob. NOT!');
你可以在这里找到一个带有测试设置的小提琴: