这个javascript属性是实例属性还是原型属性?

这个javascript属性是实例属性还是原型属性?,javascript,constructor,properties,prototype,instance,Javascript,Constructor,Properties,Prototype,Instance,我给函数赋予一个属性,并将该函数用作构造函数,如下所示: function h(){this.a='abc';} h.high='2.0'; var hinst=new h(); function hasPrototypeProperty(object, name){ return !object.hasOwnProperty(name) && (name in object); } console.log(h.hasOwnProperty('high')); //

我给函数赋予一个属性,并将该函数用作构造函数,如下所示:

function h(){this.a='abc';}
h.high='2.0';
var hinst=new h();
function hasPrototypeProperty(object, name){
    return !object.hasOwnProperty(name) && (name in object);
}
console.log(h.hasOwnProperty('high'));    //true
console.log(hinst.hasOwnProperty('high'));//false
console.log(hasPrototypeProperty(hinst, 'high'));//false
console.log('a' in hinst);   //true
console.log('high' in hinst);//false
console.log(hinst.prototype.constructor.high);   //exception
非常奇怪,在我的测试中,“high”既不是实例属性

hinst.hasOwnProperty)

或者一个原型财产

hasPrototypeProperty(hinst,'high')

最后一行抛出一个异常,说

TypeError:无法读取未定义的属性“构造函数”


我想我对属性有些误解,“hinst”怎么能访问“high”属性呢?

这里
h
是一个
函数类型的对象,您为其分配了一个名为
high
属性。因此,它与实例或原型无关。

在您的代码中,构造函数和原型之间存在一些混淆

console.log(inst.prototype.constructor.high); // exception
console.log(inst.constructor.high); // '2.0'
因为您的构造函数不是原型链的一部分。
在构造函数上定义事实之后的属性时(仅 函数)然后你就得到了这个

function h () {
this.a='abc';
}
h.high='2.0';
console.log(h);
// => { [Function: h] high: '2.0' }

一个弗兰肯斯坦函数对象怪物。

让我们稍微分解一下

这里创建了一个构造函数。它们用于
新的
操作符。一个普遍的惯例是将第一个字母大写,以使这一意图显而易见

function H(){ this.a='abc'; }
使用
new
调用构造函数时,会发生类似的情况:

(function(){
    var o = Object.create( H.prototype );
    H.apply( o, arguments );
    return o;
}());
您基本上会得到一个从
H.prototype
对象继承的新对象(
{a:'abc'}
)。也就是说,它的“内部
[[Prototype]]
属性1指向它

H.prototype
最初是一个具有单个属性的对象(
constructor
,它指向构造函数函数
H
),但您可以自由替换或扩展它。这可能是你想用这一行做的:

H.high='2.0';
但是,您将属性添加到构造函数
H
(函数也是对象)


更正的示例

函数H(){this.a='abc';}
H.prototype.high='2.0';
var hinst=新的H();
函数hasPrototypeProperty(对象、名称){
return!object.hasOwnProperty(名称)和&(对象中的名称);
}
log(H.hasOwnProperty('high')//错误的
log(hinst.hasOwnProperty('high')//错误的
log(H.prototype.hasOwnProperty('high')//符合事实的
log(hasPrototypeProperty(hinst,“high”)//符合事实的
console.log(hinst中的“a”)//符合事实的
控制台日志(hinst中的“高”)//符合事实的
console.log(H.prototype.high)//2

控制台日志(hinst.high)//2.0
high
是构造函数的属性,因此:
hinst.constructor.high
应该返回
“2.0”
hinst.constructor.hasOwnProperty('high')
=>
true
。还是有点困惑,那我怎么能让“hinst”访问“high”属性呢?@Troskyvs:把它放在
h.prototype.high
,而不是
h.high
!实例从原型继承,而不是从构造函数继承。
console.log( H.hasOwnProperty('high') );                //true
console.log( (new H()).hasOwnProperty('high') );        //false
console.log( (new H()).hasPrototypeProperty('high') );  //false