JavaScript原型属性未定义的情况。想找出原因

问题描述:

var Person = function(name){ 
    this.name = name; 
}; 
console.log("1 " + typeof(Person.prototype)) //"object" - prototype is a property of a first class functional object 

Person.prototype.sayhi = function(){console.log("hi")}; 

var john = new Person(); 

console.log("2 "+typeof(Person.sayhi)) // "undefined" 
console.log("3 "+typeof(john.sayhi))// "function" 

我想要更好地理解javascript原型。JavaScript原型属性未定义的情况。想找出原因

我不知道为什么情况2返回未定义,而情况3返回“对象”,因为它应该。

我阅读了其他帖子,但似乎无法找到答案。谢谢。

+0

看起来像一个构造函数根本就不是它自己原型的实例/克隆。 – millimoose 2013-02-13 22:05:01

+1

'typeof john.sayhi'是'function'! – Bergi 2013-02-13 22:05:08

+0

谢谢Bergi。这是一个错字。我修好了它。 – 2013-02-13 22:30:19

附加到原型的功能(Person.prototype)不能从构造函数(Person)访问,即Person.sayhi根本没有尝试访问原型。

当你调用构造函数(比如var p = new Person()),Person.prototype连接到创建的对象(p)的原型链中,这就是为什么你可以打电话p.sayhi()。然而,因为你的 “2” 的console.log不看原型sayhi永远不会附加到构造

+0

谢谢你的回答我的问题。我错误地认为Person.prototype.sayhi会将sayhi()直接附加到Person(即Person.sayhi()) – 2013-03-06 22:33:28

+0

@WilsonWang然后,请将此标记为接受的答案 – 2013-03-06 23:53:51

Person.sayHi = function() { console.log('I am not in an instance'); } 
console.log(typeof(Person.sayHi)); //"function" 
var john = new Person(); 
console.log(typeof(john.sayHi)); //"undefined" 

比不同:

Person.prototype.sayHi = function() { console.log('Hi'); } 
console.log(typeof(Person.sayHi)); //"undefined" 
console.log(typeof(Person.prototype.sayHi)); //"function" 
var john = new Person(); 
console.log(typeof(john.sayHi)); //"function" 

排序的静态方法和实例方法在c#/ java中的区别