以下内容不会引发任何错误:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
};
Function.method('inherits', function (Parent) {
this.prototype = new Parent( );
this.prototype.construct = this;
});
var p = function(){}
var c = function(){}
c.inherits(p)
但下面提到“TypeError:_a.inherits不是函数”:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
};
Function.method('inherits', function (Parent) {
this.prototype = new Parent( );
this.prototype.construct = this;
});
//var p = function(){}
//var c = function(){}
function a(){}
function b(){}
_a = new a();
_b = new b();
_a.inherits(_b)
从我读到的,new的返回值是一个函数。它必须是一个函数,因为它具有可以使用和分配的prototype属性以及指向自身的构造函数属性。在原型查找算法中,它应该在通过Object.prototype之前在Function.prototype中发现“inherits”。否?
答案 0 :(得分:0)
kid
不是函数,而是object
。您可以在此处阅读new
关键字:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
以下是基于您的代码的一些用法:
var kid = Child;
kid.inherits(Parent);
var bart = new kid();
bart.say();
答案 1 :(得分:0)
首先,new的返回值不是函数。
当使用new关键字调用函数时,会在构造函数中创建一个新对象并将其赋值给“this”并返回。
此外,创建的对象也没有原型属性。可以通过以下方式确认:
alert(typeof kid); // object
alert(kid['prototype']); //undefined
alert(kid['constructor'].prototype); //object
据我所知,通过这个构造函数的属性,原型继承有效。
答案 2 :(得分:0)
_a
不是function
它是object
而你为js inherits(Parent)
写了functions
所以
在函数上调用它,然后从继承的function
创建新对象。
例如 -
b.prototype.y=function(){ //add y to b
alert("y from b called");
}
a.inherits(b);//inherits function b
_a = new a();//create obj from a after inheritence
_a.y();// call method of b