JavaScript中函数构造函数中的函数
假设我有以下代码:JavaScript中函数构造函数中的函数,javascript,Javascript,假设我有以下代码: function Graph() { this.vertices = []; this.edges = []; } Graph.prototype = { addVertex: function(v){ this.vertices.push(v); } }; 是否可以在函数图()中添加addVertex属性名称,从而完全消除此代码的第二部分(从Graph.prototype=开始)?我试过这个,但不起作用: function Graph() {
function Graph() {
this.vertices = [];
this.edges = [];
}
Graph.prototype = {
addVertex: function(v){
this.vertices.push(v);
}
};
是否可以在函数图()
中添加addVertex
属性名称,从而完全消除此代码的第二部分(从Graph.prototype=
开始)?我试过这个,但不起作用:
function Graph() {
this.vertices = [];
this.edges = [];
addVertex = function(v){
this.vertices.push(v);
};
}
可以,您可以通过以下方式执行此操作:
function Graph() {
this.vertices = [];
this.edges = [];
this.addVertex = function(v){
this.vertices.push(v);
};
return this;
}
这将是
this.addVertex=function…
Gauvar Sacchan的答案是正确的,但如果您不想将函数附加到对象的原型,则应使用Graph.prototype.addVertex更改this.addVertex