我不明白为什么在以下代码中,obj.BaseMethod
不返回BaseClass
构造函数中定义的方法。换句话说,为什么
SubClass.prototype.BaseMethod
是定义的,但是
new SubClass().prototype.BaseMethod
不确定。
http://jsfiddle.net/hvxj4/4/
我显然在这里错过了一些重要的东西。
function BaseClass() {
var privatestuff = "blah";
return {
BaseMethod: function() {
console.log('BaseMethod called');
}
}
}
function SubClass() {
var moreprivates = "stuff";
return {
SubClassMethod: function() {
console.log('SubClassMethod called');
}
}
}
SubClass.prototype = new BaseClass();
var obj = new SubClass();
obj.SubClassMethod(); // SubClassMethod called
obj.BaseMethod(); // Uncaught TypeError: undefined is not a function
update
我实际上了解如何使用
使我的代码工作this.method = function() { }
在我的构造函数函数中。我只是不明白为什么上面的代码没有做同样的事情。
答案是,如果您在构造函数函数中返回对象,则不再使用" ProtoyPal"继承。
使我最清楚的事情是这个答案https://stackoverflow.com/a/2118831/834770
引用道格拉斯·克罗克福德(Douglas Crockford)的第5章,继承,JavaScript: (...)
道格拉斯·克罗克福德(Douglas Crockford)随后解释了新运营商的方式 作为JavaScript函数实现。此功能利用 书中定义的其他几个功能,所以我将其重写 (有点)以下更简单的形式:
function createNew(constructor) {
// a function to explain the new operator:
// var object = createNew(constructor);
// is equivalent to
// var object = new constructor();
//
// param: constructor, a function
// return: a new instance of the "constructor" kind of objects
// step 1. create a new empty object instance
// linked to the prototype of provided constructor
var hiddenLink = function(){};
hiddenLink.prototype = constructor.prototype;
var instance = new hiddenLink(); // cheap trick here: using new to implement new
// step 2. apply the constructor the new instance and get the result
var result = constructor.apply(instance); // make this a reference to instance within constructor
// step 3. check the result, and choose whether to return it or the created instance
if (typeof result === 'object') {
return object;
} else {
return instance;
}
}
因此,简而言之,如果您在此功能中返回对象,则有效地忽略了继承位。
这是一种思考语句
的方法new SubClass().prototype.BaseMethod
首先,new
关键字告诉JavaScript创建一个新的空对象,即{}
然后JavaScript设置上下文(this
)等于该新对象,并在new
之后调用该功能。因此,在这种情况下,JavaScript将寻找一个要调用的函数,但是您的语法没有引用定义的函数,因此结果是undefined
。
与定义JavaScript中定义对象的典型方法对比:
function ExampleObject() {
// stuff related to the example object
this.exampleProperty = "value";
}
var exObj = new ExampleOject();
在这种情况下,new
像以前一样创建空对象{}
,但是现在有一个定义的函数要调用。当调用此功能时,新创建的对象(设置等于this
)的exampleProperty
集将等于"value"
。然后将结果对象分配给变量exObj
。
对于来自Java背景(或类似)的人来说,这听起来很奇怪,但是JavaScript并不真正支持类的概念。该语言使不幸的是试图使其原型继承看起来像经典的继承,但实际上并不相同。如果您要在JavaScript上花费大量时间,您可能需要停止尝试在课堂和子类方面思考,而是学习一些有关原型的知识。