使用Javascript原型在对象中添加函数

时间:2015-08-21 08:32:01

标签: javascript prototype

我是Javascript的新手我试图在Object.prototype创建的对象原型中添加一些函数我试过这段代码

var a=function(){this.k="yes";}
a.prototype.b1=function(){console.log("function of a");}; 
var b=Object.create(a.prototype); 
b.prototype.c1=function(){console.log("function of b");};
b.c1();

它给我错误'无法设置属性'c1'未定义'我没有得到我在做错误的地方,请指导我。提前致谢

3 个答案:

答案 0 :(得分:2)

我不确定您到底想要做什么,但目前您的问题是b是一个普通对象(继承自a.prototype的{​​{1}}和没有.b1属性的.constructor属性)。尽管如此,你还是试图在那个不存在的东西上设置一个属性。

你要么在寻找

b.prototype

没有构造函数或var a = { b1: function(){console.log("function of a");} }; var b = Object.create(a); b.c1 = function(){console.log("function of b");}; b.c1(); b.b1(); 属性 - 只是简单的原型继承 - 或者你在寻找

.prototype

这是" class"之间继承的典型例子。结构,即带有原型对象的构造函数。您忘记了将function A() { this.k="yes"; } A.prototype.b1 = function(){console.log("function of A.prototype");}; function B() { A.call(this); } B.prototype = Object.create(a.prototype); B.prototype.c1 = function(){console.log("function of B.prototype");}; var b = new B(); b.c1(); b.b1(); 作为函数并在调用方法之前将其实例化。

答案 1 :(得分:0)

您的代码应该是这样的:

var a=function(){this.k="yes";};
a.prototype.b1=function(){console.log("function of a");}; 
var b =function(){};
b.prototype=new a(); 
b.prototype.c1=function(){console.log("function of b");};
var bObj = new b();
bObj.c1()

答案 2 :(得分:0)

你试图在这里完成两件事。

首先

var b=Object.create(a.prototype);

我假设你试图在b中扩展a类。考虑在创建后直接修改b原型:

//Create b class
var b = function(){this.key = 2};

//Extends a in b
var b.prototype = new a();

第二次

b.prototype.c1=function(){console.log("function of b");};
b.c1();

您正尝试使用b.c1();从您的班级调用您的函数。尝试先在另一个变量var bObject = new b();中实例化它,然后调用分配给te原型的函数:bObject.c1()

您的整体代码应如下所示:

//Create a class here
var a=function(){this.k="yes";};

//assign b1 function to a class
a.prototype.b1=function(){console.log("function of a");}; 

//Create b class
var b = function(){this.key = 2};

//extends a in b
b.prototype = new a();

//create c1 function in b class
b.prototype.c1=function(){console.log("function of b");};

//create bObj from b class
var bObj = new b();

//call c1 function defined in b class
bObj.c1();

//can also call b1 function from a class
bObj.b1();