我正在尝试在函数内创建方法。我可以这样做:
function sample() {};
sample.show = function() { alert() };
我会看到调用 sample.show();
的警报。但是出于代码美化的原因,我想把所有的方法声明都移到函数内部。我试过了:
function sample() {
sample.show = function() { alert() };
}
但我得到:TypeError: Object function sample() has no method 'show'
我尝试的另一种方法:
function sample() {
this.show = function() { alert() };
}
function sample() {
sample.prototype.show = function() { alert() };
}
function sample() {
this.prototype.method = function show () { alert() };
}
但结果是一样的。我什至找不到有关在函数内创建方法的任何信息。你能给我指出正确的方法吗?
UPD:我希望能够调用 sample()
函数,它也可以做一些事情。所以答案中还没有解决方案。
function sample() {
this.show = function() { alert() };
console.log('you called "sample()"');
}
sample(); // ==> you called "sample()"
最佳答案
第一次尝试:
function sample() {
sample.show = function() { alert() };
}
这只会在 sample
函数上创建一个“静态”方法,并且只会在执行它之后
console.log(sample.show);
//would show undefined on the console
sample();
console.log(sample.show);
//would then show the method definition as it has now been
//defined as a property of "sample"
第二次尝试:
function sample() {
this.show = function() { alert() };
}
这只有在您创建示例实例时才有效
console.log(sample.show);
//will print undefined as there is no property "show" on sample
sample();
console.log(window.show);
//will print the function, but since sample was executed without a
//context, show is created as a property of the global object
//in this case "window"
var d = new sample();
console.log(d.show);
//will print the function as we now have a instance of sample which
//show was made a property of
console.log(sample.prototype.show);
//will show undefined as you are not actually creating the "show" method
//on the constructor sample's prototype
现在有了原型(prototype)版本:
function sample() {
sample.prototype.show = function() { alert() };
}
有了这个之后,您将能够通过实例或原型(prototype)链访问“show”方法,但是要使原型(prototype)链调用起作用,您必须至少先创建一个实例
console.log(sample.prototype.show);
//will print undefined as "show" has not been defined on the prototype yet
var d = new sample();
console.log(d.show);
console.log(sample.prototype.show);
//Both will now print the function because the method has been defined
然而最后一个:
function sample() {
this.prototype.method = function show () { alert() };
}
根本不起作用,因为您无法直接从实例访问原型(prototype),一旦您尝试创建实例,您将收到未定义的错误。
要让它工作,你必须通过构造函数链来设置方法
function sample() {
this.constructor.prototype.method = function show () { alert() };
//is the same as doing
sample.prototype.method = function show(){ alert() };
}
总的来说,为了让你的“美化”工作,你必须首先调用 sample
,或者直接为第一个调用,或者为其他调用创建一个实例。
关于javascript - 在函数内部创建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22541712/