gpt4 book ai didi

javascript - 如何在 IIFE 中包装构造函数并将实例放置在 Window 对象上?

转载 作者:行者123 更新时间:2023-12-03 04:19:41 24 4
gpt4 key购买 nike

我想要一个文件将属性附加到 Window 对象。这是我目前拥有的代码

function Binary() {
var obj = function(msg){ console.log(msg + this.binaryString ) };
obj.binaryString = ''

Object.defineProperty(obj, 'zero', {
get: function() {
obj.binaryString += '0';
return obj;
}
});

....

return obj;
};

var binary = new Binary();

我想将整个事情包装在 IIFE 中,并将 binary 实例作为 Window 对象的属性(这将是一个库,我不希望变量名称发生冲突)。我尝试了几次不同的方法,但出现了 max callstack error 我该如何正确执行此操作?

最佳答案

基本上你这样做:

(function(){ /*Put code here.*/; window.binary = result; })()

或者用return这样:

'use strict';
window.binary = (function() {

var obj = function(msg){ console.log(msg + this.binaryString ) };
obj.binaryString = ''

Object.defineProperty(obj, 'zero', {
get: function() {
obj.binaryString += '0';
return obj;
}
});
// ...
return obj;

})();
console.log('1', window.binary);
console.log('2', binary);

/*
In modern JavaScript you may use `{...Code here...}` + `let`/`const`
as a scope, but it doesn't work for `var`s!
*/
'use strict'; // Don't forget strict mode!
{
const foo = 42;
let choo = 'Choo choo!';
var goo = 55; // Leaks!

function poo() { console.log('POO!'); }

window.bar = 'baz';
}
console.log('foo', window.foo); // undefined
console.log('choo', window.choo); // undefined
console.log('goo', window.goo); // DEFINED!
console.log('poo', window.poo); // undefined
console.log('bar', window.bar); // DEFINED!

关于javascript - 如何在 IIFE 中包装构造函数并将实例放置在 Window 对象上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44004787/

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