Javascript 子类不';不行,为什么?
这段代码来自Javascript,是解释如何创建子类的权威指南,但它不起作用 我曾经在这个网站上看到过关于如何创建子类的代码Javascript 子类不';不行,为什么?,javascript,oop,Javascript,Oop,这段代码来自Javascript,是解释如何创建子类的权威指南,但它不起作用 我曾经在这个网站上看到过关于如何创建子类的代码 function inherit(p){ if(p == null) throw TypeError(); if(Object.create) return Object.create(p); var t = typeof p; if(t != "function" || t != "object"
function inherit(p){
if(p == null) throw TypeError();
if(Object.create) return Object.create(p);
var t = typeof p;
if(t != "function" || t != "object") throw TypeError();
function f(){};
f.prototype = p;
return new f;
}
function Super_class(){
this.Sup_prop = "I'm superclass";
this.Sup_prop2 = "I'm superclass2";
}
Super_class.prototype.Hello = function(){ alert("Hello"); };
function Sub_class(){
this.sub_prop = "I'm subclass";
this.sub_prop2 = "I'm subclass 2";
}
Sub_class.prototype = inherit(Super_class);
Sub_class.prototype.constructor = Sub_class;
var x = new Sub_class;
x.Hello();
我想知道为什么我书中的代码不起作用。我的书有错或者我错了
对不起,我的英语写作不好
更新
这是我上面的第一个例子
function Super_class(){
this.Sup_prop = "I'm superclass";
this.Sup_prop2 = "I'm superclass2";
}
Super_class.prototype.Hello = function(){ alert("Hello"); };
function Sub_class(){
this.sub_prop = "I'm subclass";
this.sub_prop2 = "I'm subclass 2";
}
Sub_class.prototype = new Super_class;
var x = new Sub_class; // change here
x.Hello();// It work!!
我想知道为什么“Sub_class.prototype.constructor”设置为Sub_class?
我的书没有解释。你应该通过
Sub_class.prototype = inherit(Super_class);
Sub_class.prototype.constructor = Sub_class; //Why did set be Sub_class??
而不是继承函数的超级类。它似乎期望一个原型对象,而不是函数本身。问题在于您的
继承函数,特别是这一行:
Super_class.prototype
这将返回一个新对象,其原型设置为p
。但是,p
不是Super_类的一个实例
;这是函数Super\u类
。我不确定当它接收一个对象作为参数时,你想用inherit
做什么,但当它接收一个函数时,你不想使用object.create
。请尝试从以下内容开始:forinherit
:
if(Object.create) return Object.create(p);
它以什么方式不起作用?症状是什么?警报不起作用。当我在web浏览器中进行测试时,它会显示错误消息“hads not method Hello”。这是错误的。整个参数列表(包括括号)是可选的。例如,我同意你的观点。它没有参数,可以避免。@TedHopp是的,我意识到了我的错误。我以前从未见过这种语法。当我在小提琴上测试这个问题时,我意识到我错了。@ben336非常感谢!!,它起作用了。我想知道一些事情。你能告诉我为什么“Sub_class.prototype.constructor”设置为“Sub_class”?。我的书没有对此的解释。@Domino抱歉,我不理解你的问题。你能详细说明一下吗?谢谢你的建议!!。:)
function inherit(p) {
if (typeof p === 'function') {
return new p;
}
throw TypeError()
}