gpt4 book ai didi

javascript - 无法实现模块模式

转载 作者:行者123 更新时间:2023-12-04 01:11:58 24 4
gpt4 key购买 nike

我正在尝试从 Douglas Crockford 的“Javascript:The Good Parts”一书中复制一些代码。思路是使用闭包进行对象封装,避免Javascript固有的全局变量。

var serial_maker = function (  ) {

// Produce an object that produces unique strings. A
// unique string is made up of two parts: a prefix
// and a sequence number. The object comes with
// methods for setting the prefix and sequence
// number, and a gensym method that produces unique
// strings.

var prefix = '';
var seq = 0;
return {
set_prefix: function (p) {
prefix = String(p);
},
set_seq: function (s) {
seq = s;
},
gensym: function ( ) {
var result = prefix + seq;
seq += 1;
return result;
}
};
}( );

var seqer = serial_maker( );
seqer.set_prefix = 'Q';
seqer.set_seq = 1000;
var unique = seqer.gensym( ); // unique is "Q1000"

Chrome 正在拾取错误:

Uncaught TypeError: Property 'serial_maker' of object [object DOMWindow] is not a function (anonymous function)

我做错了什么?

编辑:我应该说这段代码完全是从书中复制粘贴的......

最佳答案

您正在尝试将函数的结果作为函数执行,并且正在为函数赋值。尝试:

var seqer = serial_maker;
seqer.set_prefix('Q');
seqer.set_seq(1000);
var unique = seqer.gensym();

另见 jsFiddle

关于javascript - 无法实现模块模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5156761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com