从函数内部调用函数?
我有以下代码:从函数内部调用函数?
var A = function (id) {
var elem = document.getElementById(id);
function text() {
return "Hello world";
}
this.other = function(){
console.log(text());
}
}
如果我想从外面添加other
功能,还自称喜欢这个文本()函数:
(function(A){
A.prototype.other = function() {
console.log(text());
}
})(A);
有没有办法做到那?我的意思是,无需更改function text(){}
到this.text=function(){}
您可以附加text()
方法A
函数,它仍然是一个对象,然后在A.prototype.other
这样使用它。
var A = function(id) {
this.id = id;
}
A.text = function() {
return "Hello world";
}
A.prototype.other = function() {
return this.id + ' ' + A.text();
}
var a = new A(123);
console.log(a.other())
如果它工作,如果我使它'a = new A(“canvas_id”);'比这可能是解决方案。我可以吗? – IchHabsDrauf
什么是“canvas_id”? –
你问我,因为我写了'var a = new A',如果你是这样的,你可以,如果你没有传入任何参数给构造函数,你不必写'A()'你可以写'A'但它是一样的东西。 –
** **为什么你不希望改变'功能文本(){}''到= this.text功能(){}'? – phihag
因为我不希望它被覆盖。 'var a = new A(); a.text = function(){}' – IchHabsDrauf
然后你的问题应该是'我如何防止名称被覆盖',并提及为什么[属性](https://developer.mozilla.org/en/docs/ Web/JavaScript/Reference/Global_Objects/Object/defineProperty)是不够的。您也应该考虑是否要包含随机覆盖其他库名称的代码。 – phihag