2017-04-15 186 views
1

我有以下代码:从函数内部调用函数?

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(){}

+0

** **为什么你不希望改变'功能文本(){}''到= this.text功能(){}'? – phihag

+0

因为我不希望它被覆盖。 'var a = new A(); a.text = function(){}' – IchHabsDrauf

+0

然后你的问题应该是'我如何防止名称被覆盖',并提及为什么[属性](https://developer.mozilla.org/en/docs/ Web/JavaScript/Reference/Global_Objects/Object/defineProperty)是不够的。您也应该考虑是否要包含随机覆盖其他库名称的代码。 – phihag

回答

1

您可以附加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())

+0

如果它工作,如果我使它'a = new A(“canvas_id”);'比这可能是解决方案。我可以吗? – IchHabsDrauf

+0

什么是“canvas_id”? –

+0

你问我,因为我写了'var a = new A',如果你是这样的,你可以,如果你没有传入任何参数给构造函数,你不必写'A()'你可以写'A'但它是一样的东西。 –