在函数内部创建方法

Create method inside function

本文关键字:方法 创建 内部 函数      更新时间:2023-09-26

我试图在函数内创建方法。我可以这样写:

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

这只会在你创建一个sample

的实例时起作用
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,要么直接调用第一个,要么为其他的创建一个实例。

示例函数中的代码在sample被调用之前不会被执行。所以你可以让你的例子工作通过这样做:

function sample() {
    sample.show = function() { alert() };
}
sample()
sample.show()

你可以试试:

function sample() {
    this.show = function() { alert() };
}
var x = new sample();
x.show();

你需要让sample成为一个对象

var sample = {
  this.show = function() { alert() };
}