我很困惑,为什么我在这里得到这个错误。我想要一些启发。JavaScript对象原型似乎破碎
function c(me) { this.me = me; }
c.prototype.identify = function() { return "I am " + this.me; };
function d(me) { c.call(this, me); }
d.prototype = Object.create(c.prototype);
d.prototype.speak = function() { return "Hello, " + this.identify() + "." };
var d1 = new d("d1");
var d2 = new d("d2");
console.log(d1.speak());
console.log(d2.speak());
console.log(d.speak()); //returns: TypeError: d.speak is not a function
returns: TypeError: d.speak is not a function
我明确地将属性添加到speak
d.prototype
。实际上,d1
和d2
都可以访问其原型层次结构中的属性/函数。但是当我试图在d
上调用它时,我得到一个TypeError。我尝试了各种“调整”,无济于事。为了排除任何范围问题,我尝试在IIFE中包装各种部分,但它没有效果。我从最后一行
console.log(d.speak); //returns: undefined
,并得到undefined
删除()
。这告诉我speak
不是d
有权访问的属性/函数。即。将speak
更改为blah
,并获取登录到控制台的相同undefined
。
console.log(d.blah); //returns: undefined
我知道我错过了一些可能对一组新的眼睛很明显的小东西。
'd.speak()'不会工作,因为你已附上'说话()'函数到'D'的原型对象函数,而不是'd'函数本身。因此,无论是需要将'speak()'函数附加到'd'本身,比如'd.speak = function(){}'或调用'd.prototype.speak()'来调用它。 –
我不知道你期望'd.speak()'返回什么结果? – Oriol
@Oriol,'你好,我没有定义。'是我的期望。 – ppovoski