我正在尝试在函数内创建方法。我可以这样做:
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()"
答案 0 :(得分:4)
首次尝试:
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
现在有了原型版本:
function sample() {
sample.prototype.show = function() { alert() };
}
通过此操作,您将能够访问" show"方法要么通过实例,要么来自原型链,但是对于原型链调用来说,你必须至少先制作一个实例
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() };
}
根本无法正常工作,因为您无法直接从实例访问原型,一旦您尝试创建实例,您将收到未定义的错误。
要使它工作,你必须通过构造函数链来设置方法
function sample() {
this.constructor.prototype.method = function show () { alert() };
//is the same as doing
sample.prototype.method = function show(){ alert() };
}
总的来说,你的美化"为了工作,你必须先直接调用sample
,直接调用第一个,或者为其他人创建一个实例。
答案 1 :(得分:1)
在调用sample之前,不会执行sample函数中的代码。所以你可以通过这样做来让你的榜样起作用:
function sample() {
sample.show = function() { alert() };
}
sample()
sample.show()
答案 2 :(得分:0)
你可以试试这个:
function sample() {
this.show = function() { alert() };
}
var x = new sample();
x.show();
答案 3 :(得分:-2)
您需要将样本设为对象
var sample = {
this.show = function() { alert() };
}