诡异的js闭包问题的解决.

上次pro js读书笔记里面,我说有段代码书里面有错,可是自己不知道怎么改,偶然的机会在g9 老大的blog上看到了解决方法。

http://blog.youkuaiyun.com/g9yuayon/archive/2007/04/18/1568980.aspx

错误代码:
[code]function User( properties ) {
var temp=this;
for ( var i in properties ) { (function(){

temp[ "get" + i ] = function() {
return properties[i];
};

temp[ "set" + i ] = function(val) {
properties[i] = val;
};
})(); }
}

var user = new User({
name: "Bob",
age: 44
});
alert( user.getname() );

alert( user.getage()); [/code]

此时的结果将会打印出两个44,有关这点g9的blog上这样的解答:
[quote]
JavaScript的Closure环境由静态的句法结构确定。也就是说,代码一旦写成,我们就知道函数的自由变量同哪些环境里的变量绑定。因此,虽然运行时同一个内函数被调用多次,创建了多个闭包,这些闭包指向的都是同一个环境里的同一个变量。这样同JavaScript规定的闭包语义一致。[/quote]

[color=red]这句不是很理解,望那个达人能够解释一下.[/color]

于是我们进行改进我们可以加进去一个叫做factor function的东东。
请看改写后的代码.

[code]function User( properties ) {
var temp=this;
for ( var i in properties ) {
(function(i){
temp[ "get" + i ] = function() {
return properties[i];
};
temp[ "set" + i ] = function(val) {
properties[i] = val;
};
})(i);
}
}

var user = new User({
name: "Bob",
age: 44
});


alert( user.getname());
user.setname("bobo");
alert(user.getname());
alert( user.getage()); [/code]

这样就可以打印出正确的结果了.
RK3588平台开发系列讲解(以太网篇)MDIO底层驱动 沉淀、分享、成长,让自己和他人都能有所收获!😄。 阅读详情

相关推荐

【计算机视觉学习03】全景图像拼接

文章目录一、基本原理1.1 图像拼接的几何原理1.2 直线,圆,复杂曲线方程拟合1.3 RANSAC算法1.4 APAP算法1.5 寻找最佳拼接缝(Seam Finding)1.5.1 最大流问题1.5.2 最大流问题的增广链算法1.5.3 最大流最小割定理二、 图像拼接具体实现2.1 代码2.2 运行结果 一、基本原理 将两幅或多幅具有重叠区域的图像,通过特征匹配将具有相同的特征点(SIFT特征点)的图像拼接在一起,将来自多个不同视角拍摄的图像变换到同一视角下,拼接成一张宽视野图像。 图像拼接基础流程

一个正在努力学习的iter 7789

js中的闭包问题、call/apply/bind 区别

js中的闭包问题、call/apply/bind 区别 函数中的局部变量当函数执行完成之后,局部变量就会被销毁 垃圾回收机制,将不需要使用数据进行清除,如果不清除就会造成内存泄漏 闭包: 函数套函数,执行外部函数时返回内部函数 并且内部函数有权调用外部函数作用域中局部变量 当引用js文件中变量名相同时,我们把这种叫做变量污染 闭包会产生私有变量的存在,解决变量污染问题 但是也会产生内存泄漏 // 常见闭包 function fn(){ var a = 1; function fn1(){

qq_37905131的博客 386

E-Prime脑电实验打mark全攻略:从端口查询到串并口实战(附常见问题解决)

本文提供了E-Prime脑电实验打mark的完整实战指南,涵盖端口查询、并口与串口配置的核心步骤及常见问题解决。文章深入解析了mark原理,并详细介绍了通过E-Basic脚本和Serial设备对象发送信号的两种方法,帮助研究者实现E-Prime与脑电设备的高精度时间同步,确保实验数据可靠性。

4k5l6j7h8的博客 355

不要3分钟简单理解闭包

摘要: 由于函数外部是不能访问函数内部局部变量(私有属性)。因为,函数内部的变量,在函数执行完毕以后,就会被释放掉。 不能直接访问那就间接去实现,先看例子 <script> var a = 200; function Fn () { var a = 100; return function () { console.l...

weixin_30546189的博客 150

基于Qwen3-14B大模型的智能UI自动化测试实践

UI自动化测试是软件工程中保障产品质量的关键环节,其核心原理是通过脚本模拟用户操作,对软件界面进行功能验证。传统方法依赖于编写和维护基于元素定位的固定规则脚本,在面对复杂交互或频繁变化的界面时,维护成本高昂。大语言模型(LLM)的出现为这一领域带来了新的技术价值,其强大的自然语言理解和代码生成能力,使得测试脚本的编写从精确编码转向了任务描述。通过将大模型作为决策大脑,结合Playwright等自动化工具作为执行器,可以构建出能够理解界面、规划操作并验证结果的智能测试系统。这种方案特别适用于处理变化频繁、逻辑

weixin_42619742的博客 303

CISP-PTE考前实操练习题

CISP-PTE考前学习练习题目,渗透测试功工程师

2301_79546223的博客 2000

四个问题彻底学会JS中“闭包”

目录 闭包是什么? 闭包怎么用? 闭包有什么用? 闭包的优缺点是什么? 1.闭包是什么? 闭包:它是一种手段,通过它,内部函数在其父函数结束之后依然可以引用其外围函数中的变量。 我们知道在js作用域环境中访问变量的权利是由内向外的,内部作用域可以获得当前作用域下的变量并且可以获得当前包含当前作用域的外层作用域下的变量,反之则不能,也就是说在外层作用域下无法获取内层作用域下的变量,同样在不同的函...

前端-阿来 375

从Mate到Mate40 Pro+:华为旗舰核心配置演进与选购避坑指南

本文回顾了华为Mate系列从初代到Mate40 Pro+的核心配置演进历程,重点分析了处理器性能、影像系统、屏幕设计及续航快充的技术突破。针对选购需求,提供了区分版本、5G选择及存储配置的实用避坑建议,帮助消费者明智选择华为旗舰机型。

weixin_30015371的博客 494

关于js闭包、关于call()、apply()、bind()等方法的一点理解

一、js闭包 首先,需要搞清楚什么是闭包: 闭包是嵌套的内部函数 有点抽象,上例子: function outExample(){ var a=1 function innerExample(){ return a*a //这里的a调用的不是全局变量,而是outExample中的函数局部变量 } } 1.2、产生闭包的条件 1、函数

m0_57446284的博客 339

图解目标检测 之 YOLO 算法 最全原理详解

YOLO 一.背景 YOLO(You Only Look Once: Unified, Real-Time Object Detection),是Joseph Redmon和Ali Farhadi等人于2015年提出的基于单个神经网络的目标检测系统。在2017年CVPR上,Joseph Redmon和Ali Farhadi又发表的YOLO 2,进一步提高了检测的精度和速度。 二.YOLO算法的网...

DFCED的博客 26万+

SAP PS 收入确认方法配置清单(成本推导收入 / 项目进度推导收入)

摘要:本文详细介绍了SAPPS模块中两种收入确认方法的配置流程:成本推导收入(成本比例法)和项目进度推导收入(里程碑法)。通过事务码OKG1-OKG5等关键配置步骤,分别实现基于累计成本比例和里程碑完成权重的收入确认逻辑。文章对比了两种方法的适用场景和管控要点:成本法适用于成本与进度强相关的项目,需严控预计总成本;进度法则依赖明确的里程碑验收。同时提供了落地建议,包括项目类型绑定、数据校验和变更管控等最佳实践,为SAPPS系统收入确认功能实施提供完整指导。

金牌架构师 952

js闭包处理

所以,如果你把父函数当作对象(object)使用,把闭包当作它的公用方法(Public Method),把内部变量当作它的私有属性(private value),这时一定要小心,不要随便改变父函数内部变量的值。原因就在于f1是f2的父函数,而f2被赋给了一个全局变量,这导致f2始终在内存中,而f2的存在依赖于f1,因此f1也始终在内存中,不会在调用结束后,被垃圾回收机制(garbage collection)回收。但是,前面已经说过了,正常情况下,这是办不到的,只有通过变通方法才能实现。

Wzc0720的博客 966

图神经网络实战(25)——基于A3T-GCN预测交通流量

本节重点讨论了使用 TGNN 进行交通预测任务。首先,我们介绍了 PeMS-M 数据集,并将其从表格数据转换为具有时间信号的静态图数据集。在实践中,我们根据输入距离矩阵创建了加权邻接矩阵,并将交通速度转换为时间序列。最后,我们构建了 A3T-GCN 模型,这是一个专为交通预测设计的 T-GNN 模型,并将结果与两个基线模型进行了比较,验证了模型的预测结果。

盼小辉丶的博客 8595

诡异的JavaScript Closure

出来混,迟早要还。今天写JavaScript代码,才知道一个循环里的函数共享同一闭包 三个闭包共享一个变量。比如下面的代码是错的,不能正确报告每个事件对应的描述:var div = document.getElementById("testDiv");var events = {onclick: "clicked", onchange: "changed",  onmouseover: "

负暄琐话 1万+

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

JS 循环绑定多个元素的点击事件时出现的闭包问题与解决方案

昨天在循环绑定多个a标签的点击事件时出现了不少问题,首先是 js 的典型闭包问题,这个还好以前也遇到过,于是很快解决了,但是在为多个a标签绑定点击事件成功之后,本来以为就大功告成了,结果居然是在页面加载时就自动全部a标签的点击事件自动触发了,很纳闷!!!至今还是没搞明白。测试后发现貌似是使用了闭包时才会导致此问题的发生,以下是自己写的一段建议的测试代码(仅为了说明问题而已,所以较为简陋!):

Inite的博客 1951

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

javascript闭包诡异的问题

var funcs = []; for (var i = 0; i &lt; 3; i++) { // let's create 3 functions funcs[i] = function() { // and store them in funcs console.log("My value: " + i); // each should log i...

weixin_33969116的博客 69

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

JavaScript闭包:优雅掌控作用域的艺术

闭包的本质是函数与其词法环境的绑定。当一个内部函数访问其外部作用域的变量时,就形成了闭包。let count = 0 // 被闭包捕获的变量当执行完毕后,其作用域依然被返回的匿名函数引用,形成独立的作用域闭包。

BANaanaa的博客 927

vue中methods中的方法闭包缓存问题

问题背景 需求描述 在路由的导航栏中需要, 判断是否为第一次点击 需要一个标志位来记录是否点击过 现状: 这个标志位只在一个函数中用过.不希望存放全局 希望在这个methods中形成闭包, 用来缓存这个函数 做出如下尝试后, 发现可以实现. 当前问题: 不能在闭包调用时找到正确的this. 诡异点 测试使用时: 返回的this找到了window // 测试使用: <div id="app"> <button @click="test">

Jack, what else can you do besides holding your little darling? 521

细品JS的寻址,闭包,对象模型和相关问题

原贴地址:http://infinte.yo2.cn/archives/633839似乎某些程序员的集合是不相交的,就好像JS程序员和玩编译原理和CPU指令的汇编程序员就几乎没有交叉。前些日子讨论的火热的“作用域链”问题,说白了就是寻址问题,不过,这个在C中十分简单的问题却被JS这个动态语言弄得很复杂。正是因为JS是动态语言,所以JS的寻址是现场寻址,而非像C一样,编译后确定。此外,JS引

sunxing007的专栏 3345

javascript 中的暗物质 - 闭包

1. 诡异的闭包 javascript 中有一个特殊的特性 - 闭包,对于 .NET 程序员来说,比较熟悉的是面向对象的程序设计 OOP, 而来自函数式语言的闭包则显得比较诡异,许多程序员对它敬而远之。 对于闭包我们还是要从函数式语言的特点说起。 不知道你有没有发现,在 javascript 中没有 public ,private 之类的关键字,也没有 class ,虽然也存在对象一说,但是对...

ziqi688的博客 69

js闭包的理解-目前网上分析的最透彻文章

js的闭包对于大家实际上并不陌生,但是真正敢说自己完全理解的人并不多。笔者在网上看到分析闭包的文章非常多,篇幅用的非常多,但是实际上分析的并不到位,或者根本就是不正确的。我有时候都在想,写这些文章的人自己未必真的理解了。今天我就为大家说到说到js的闭包,看完你百分百的能够理解。 说闭包之前,我们先要说一个js的概念 js的变量不是传统意义的变量,是一个广义的概念 例如: 1、va...

dizhang8888的博客 139

JavaScript 执行机制深度解析:从 V8 引擎到作用域链、变量提升与闭包的全面剖析

你是否曾遇到过以下“诡异”现象?函数在声明前就能调用?输出undefined而不是报错?循环中的setTimeout全部输出同一个值?在if块中用var声明变量,却影响了整个函数?这些看似“反直觉”的行为,其实都源于 JavaScript 引擎底层的执行机制。JS 是如何运行的?什么是执行上下文(Execution Context)?变量提升(Hoisting)是怎么回事?作用域(Scope)到底是什么?为什么letconst比var更安全?V8 引擎内部是如何处理这些概念的?

jj1245_的博客 584

JavaScript中的闭包

闭包的特点与形式        闭包,作为一种特殊的结构,有其自身的特点和各种形式。闭包的内在:自治的领域       闭包的“闭”是指闭包的内部环境对外部不可见,也就是说闭包具有控制外部域的能力但是又能防止外部域对闭包的反向控制。换句话说,闭包的领域是对外封闭的。       闭包的这一个特点不用过多解释,因为JavaScript闭包是通过function实现的,所以它天然具有基

林天问de博客 699
上一篇: 爱上Ellen Page
下一篇: 今天把emacs鼓捣了一整天。
interhanchi
博客等级 码龄23年 19粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值