“我如何找到?”;原型;javascript中的值?
我使用以下函数来检测属于对象构造函数而不是对象本身的值“我如何找到?”;原型;javascript中的值?,javascript,inheritance,Javascript,Inheritance,我使用以下函数来检测属于对象构造函数而不是对象本身的值 function isAPrototypeValue(object, key ) { return !(object.constructor && object.constructor.prototype[key]); } 这项工作如下: Array.prototype.base_value = 'base' var array = new Array; array.custom_value = 'custom' al
function isAPrototypeValue(object, key ) {
return !(object.constructor && object.constructor.prototype[key]);
}
这项工作如下:
Array.prototype.base_value = 'base'
var array = new Array;
array.custom_value = 'custom'
alert( isAPrototypeValue( array, 'base_value' ) ) // true
alert( isAPrototypeValue( array, 'custom_value' ) ) // false
但是当我开始使用继承时:
function Base() {
return this
};
Base.prototype.base_value = 'base';
function FirstSub() {
return this
};
FirstSub.prototype = new Base();
FirstSub.prototype.first_value = 'first';
function SubB () {
return this
};
SecondSub.prototype = new FirstSub();
SecondSub.prototype.second_value = 'second';
result = new SecondSub();
我打电话
alert( result.constructor )
我会得到Base,而不是预期的SecondSub,这本身并不是一个大问题,但是
如果我像这样扩展结果:
result.custom_value = 'custom'
result.another_value = 'another'
我希望能够区分属于结果的值或属于第二子类、第一子类和基本类的值
例如
如何更改isAPrototypeValue以产生预期的结果?我想您可能想回顾一下Douglas Crockford用JavaScript编写的关于继承的文章。他在书中有一些,在关于YUI剧院的演讲中也有一些。有关将对象特性与其派生对象的特性区分开来的信息,请参见。Crockford似乎认为在JavaScript中使用经典继承是可能的,但不是开发语言功能的最佳方式。也许这会给你一些想法,告诉你如何着手解决你想要完成的事情。祝你好运 关于继承的Crockford:
function Base() {
return this
};
Base.prototype.base_value = 'base';
function FirstSub() {
return this
};
FirstSub.prototype = new Base();
FirstSub.prototype.first_value = 'first';
function SubB () {
return this
};
SecondSub.prototype = new FirstSub();
SecondSub.prototype.second_value = 'second';
result = new SecondSub();
function Base() {
return this
};
Base.prototype.base_value = 'base';
function FirstSub() {
return this
};
FirstSub.prototype = new Base();
FirstSub.prototype.first_value = 'first';
function SubB () {
return this
};
SecondSub.prototype = new FirstSub();
SecondSub.prototype.second_value = 'second';
result = new SecondSub();