this、apply、call、bind

一文讲清楚this的指向性问题以及call、apply、bind关于this的指向绑定 阅读详情

this 的指向

在 ES5 中,其实 this 的指向,始终坚持一个原理: this 永远指向最后调用它的那个对象。

例子1:

  var name = "windowsName";
    function a() {
        var name = "Cherry";

        console.log(this.name);           

        console.log("inner:" + this);    
    }
    a();
    console.log("outer:" + this)      

例子2:

    var name = "windowsName";
    var a = {
        name: "Cherry",
        fn : function () {
            console.log(this.name);       
        }
    }
    a.fn();

例子3:

var name = "windowsName";
    var a = {
        name: "Cherry",
        fn : function () {
            console.log(this.name);      
        }
    }
    window.a.fn();

例子4:

    var name = "windowsName";
    var a = {
        // name: "Cherry",
        fn : function () {
            console.log(this.name);       
        }
    }
    window.a.fn();

例子5:

    var name = "windowsName";
    var a = {
        name : null,
        // name: "Cherry",
        fn : function () {
            console.log(this.name);      
        }
    }

    var f = a.fn;
    f();

例子6:

 var name = "windowsName";

    function fn() {
        var name = 'Cherry';
        innerFunction();
        function innerFunction() {
            console.log(this.name);      
        }
    }

    fn()

如何改变this指向

  • 使用ES6箭头函数
  • 函数内部使用 that=this
  • 使用 apply、call、bind
  • new实例化对象

例子7:

    var name = "windowsName";

    var a = {
        name : "Cherry",

        func1: function () {
            console.log(this.name)     
        },

        func2: function () {
            setTimeout(  function () {
                this.func1()
            },100);
        }

    };

    a.func2()     

最后调用 setTimeout 的对象是 window,但是在 window 中并没有 func1 函数。

箭头函数

ES6 的箭头函数是可以避免 ES5 中 this 的指向问题,箭头函数的 this 始终指向函数定义时的 this,而非执行时。,箭头函数需要记着这句话:“箭头函数中是没有 this 绑定,必须通过查找作用域链来决定其值,如果箭头函数被非箭头函数包含,则 this 绑定的是最近一层非箭头函数的 this,否则,this 为 undefined”。

例子8:

    var name = "windowsName";

    var a = {
        name : "Cherry",

        func1: function () {
            console.log(this.name)     
        },

        func2: function () {
            setTimeout( () => {
                this.func1()
            },100);
        }

    };

    a.func2()     

在函数内部使用 that = this

例子9:

    var name = "windowsName";

    var a = {

        name : "Cherry",

        func1: function () {
            console.log(this.name)     
        },

        func2: function () {
            var _this = this;
            setTimeout( function() {
                _this.func1()
            },100);
        }

    };

    a.func2()       

这里的 this 是调用 func2 的对象 a,为了防止在 func2 中的 setTimeout 被 window 调用而导致的在 setTimeout 中的 this 为 window。我们将 this(指向变量 a) 赋值给一个变量 _this,这样,在 func2 中我们使用 _this 就是指向对象 a 了。

使用 call、apply、bind

 var name = "windowsName";   
 var a = {
        name : "Cherry",

        func1: function () {
            console.log(this.name)
        },

        func2: function () {
            setTimeout(  function () {
                this.func1()
            }.apply(a),100); //call(a),100); //bind(a)(),100);
        }

    };

    a.func2()         

call:

function.call(thisArg, arg1, arg2, ...)

1.call 可以接受多个参数,第一个参数是this 指向的对象,之后的是函数回调所需的入参

function add(a, b) {
  return a + b;
}

add.call(this, 1, 2) // 3

2.call 方法可以指定this 的指向(即函数执行时所在的的作用域),然后再指定的作用域中,执行函数

var obj = {};
var f = function(){
return this;
};
console.log(f() === window);  // this 指向window
console.log(f.call(obj) === obj)  ////改变this 指向 obj

3.call 方法的参数,应该是对象obj,如果参数为空或null,undefind,则默认传参全局对象

var n = 123;
var obj = { n: 456 };

function a() {
  console.log(this.n);
}

a.call() // 123
a.call(null) // 123
a.call(undefined) // 123
a.call(window) // 123
a.call(obj) // 456

4.call方法的一个应用是调用对象的原生方法。

var obj = {};
obj.hasOwnProperty('toString') // false

// 覆盖掉继承的 hasOwnProperty 方法
obj.hasOwnProperty = function () {
  return true;
};
obj.hasOwnProperty('toString') // true

Object.prototype.hasOwnProperty.call(obj, 'toString') // false

hasOwnProperty是obj对象继承的方法,如果这个方法一旦被覆盖,就不会得到正确结果。call方法可以解决这个问题,它将hasOwnProperty方法的原始定义放到obj对象上执行,这样无论obj上有没有同名方法,都不会影响结果。

apply:

apply方法的作用与call方法类似,也是改变this指向,然后再调用该函数。唯一的区别就是,它接收一个数组作为函数执行时的参数,使用格式如下。

func.apply(thisArg, [arg1, arg2, ...])

apply方法的第一个参数也是this所要指向的那个对象,如果设为null或undefined,则等同于指定全局对象。第二个参数则是一个数组,该数组的所有成员依次作为参数,传入原函数。原函数的参数,在call方法中必须一个个添加,但是在apply方法中,必须以数组形式添加。

function f(x, y){
  console.log(x + y);
}

f.call(null, 1, 1) // 2
f.apply(null, [1, 1]) // 2

f函数本来接受两个参数,使用apply方法以后,就变成可以接受一个数组作为参数

(1)找出数组最大元素

JavaScript 不提供找出数组最大元素的函数。结合使用apply方法和Math.max方法,就可以返回数组的最大元素。

var a = [10, 2, 4, 15, 9];
Math.max.apply(null, a) 

(2)将数组的空元素变为undefined

空元素与undefined的差别在于,数组的forEach方法会跳过空元素,但是不会跳过undefined。因此,遍历内部元素的时候,会得到不同的结果。

var a = ['a', , 'b'];

function print(i) {
  console.log(i);
}

a.forEach(print)
// a
// b

Array.apply(null, a).forEach(print)
// a
// undefined
// b

(3)转换类似数组的对象

另外,利用数组对象的slice方法,可以将一个类似数组的对象(比如arguments对象)转为真正的数组。

Array.prototype.slice.apply({0: 1, length: 1}) // [1]
Array.prototype.slice.apply({0: 1}) // []
Array.prototype.slice.apply({0: 1, length: 2}) // [1, undefined]
Array.prototype.slice.apply({length: 1}) // [undefined]

注:对象必须有length属性,以及相对应的数字键。

bind:

bind方法用于将函数体内的this绑定到某个对象,然后返回一个新函数。(返回一个原函数的拷贝,并拥有指定的 this 值和初始参数)

function.bind(thisArg[, arg1[, arg2[, ...]]])

如果bind方法的第一个参数是null或undefined,等于将this绑定到全局对象,函数运行时this指向顶层对象(浏览器为window)。

例1:

var d = new Date();
d.getTime() // 1481869925657

var print = d.getTime;
print() // Uncaught TypeError: this is not a Date object.

上述代码,我们将d.getTime方法赋给变量print,然后调用print就报错了。这是因为getTime方法内部的this,绑定Date对象的

实例,赋给变量print以后,内部的this已经不指向Date对象的实例了。

例2:

我们使用bind方法可以解决这个问题:

var print = d.getTime.bind(d);
print() // 1481869925657

 

例3:绑定自身对象

var counter = {
  count: 0,
  inc: function () {
    this.count++;
  }
};

var func = counter.inc.bind(counter);
func();
counter.count // 1

上面代码中,counter.inc方法被赋值给变量func。这时必须用bind方法将inc内部的this,绑定到counter,否则就会出错。

例4:绑定其它对象

var counter = {
  count: 0,
  inc: function () {
    this.count++;
  }
};

var obj = {
  count: 100
};
var func = counter.inc.bind(obj);
func();
obj.count // 101

上面代码中,bind方法将inc方法内部的this,绑定到obj对象。结果调用func函数以后,递增的就是obj内部的count属性。

例5 

bind方法每运行一次,就返回一个新函数,这会产生一些问题。比如,监听事件的时候,click事件绑定bind方法生成的一个匿名函数。这样会导致无法取消绑定

element.addEventListener('click', o.m.bind(o));
element.removeEventListener('click', o.m.bind(o));

正确的方法是写法:

var listener = o.m.bind(o);
element.addEventListener('click', listener);
//  ...
element.removeEventListener('click', listener);

区别:

例1

  var a ={
        name : "Cherry",
        fn : function (a,b) {
            console.log( a + b)
        }
    }

    var b = a.fn;
    b.apply(a,[1,2])     // 3

例2 

 var a ={
        name : "Cherry",
        fn : function (a,b) {
            console.log( a + b)
        }
    }

    var b = a.fn;
    b.call(a,1,2)  // 3

apply 和 call 的区别是 call 方法接受的是若干个参数列表,而 apply 接收的是一个包含多个参数的数组。

例3

    var a ={
        name : "Cherry",
        fn : function (a,b) {
            console.log( a + b)
        }
    }

    var b = a.fn;
    b.bind(a,1,2)

bind()方法创建一个新的函数, 当被调用时,将其this关键字设置为提供的值,在调用新函数时,在任何提供之前提供一个给定的参数序列。MDN

因此我们需手动调用

    var a ={
        name : "Cherry",
        fn : function (a,b) {
            console.log( a + b)
        }
    }

    var b = a.fn;
    b.bind(a,1,2)()           // 3

总结

1. call 、 apply 、bind 均能改变this 指向

2. bind 每次执行产生一个新函数,call、apply 不会

3. call ,bind 接收多个参数绑定到函数,参数单一传入,apply 接收方式为数组

 

参考:

https://juejin.im/post/6844903496253177863

https://javascript.ruanyifeng.com/oop/this.html#toc7

 

详解JS中的this、apply、call、bind(经典面试题) JS中的this、apply、call、bind是一道经典面试题,最好还是了解一下 this 的指向和 call、apply、bind 三者的区别。下面就跟随脚本之家小编一起学习this、apply、call、bind的知识吧 立即下载

相关推荐

卫星图像检测,分割,跟踪,超分辨率,数据集调研,以及论文笔记

目标检测,针对物体有很多类如桥,烟囱,罐子等,有静态图像下的检测,也就是图像源头多来自谷歌地图,但是前后帧没有任何联系,并且谷歌地图相对来说比较清楚,难度小一点,也有粗粒度以及较细粒度的检测,然后卫星视频的数据集较少,则可以通过前后帧的联系来辅助检测,并且卫星帧基本上只对车,船,飞机,火车进行检测,没有进行细粒度的检测即将车辆分类为卡车,皮卡,小轿车,但是关船,则可以分类为货船以及军舰,因为目前的卫星视频中小车实在太少了,难以进行更细粒度的检测。luojia 三号卫星。

zhangzhao147的博客 4706

SpringBoot实现许可证控制指南

本文介绍了TrueLicense的License控制核心原理及实现步骤。TrueLicense采用公钥密码学原理,通过非对称加密算法生成密钥对,确保License文件无法被篡改和伪造。实现过程分为生成端和客户端两部分:生成端使用私钥对授权信息签名生成License文件,客户端内置公钥进行验证。文章详细说明了密钥对生成、License生成端和客户端的代码实现,包括依赖引入、授权参数定义、硬件信息获取等关键步骤。同时提供了进阶建议,如自定义验证增强安全、项目结构规划、代码混淆等,以构建更健壮的授权系统。通过合理

油墨香^-^的博客 424

电流模架构Bandgap设计与仿真

带隙基准作为集成电路中一个重要模块,被广泛应用在低压差线性稳压(LDO)、充电电池保护芯片和通信电路、射频收发器、flash存储器等多种模拟及数模混合集成电路中,并且是片上集成系统(SOC)芯片中不可或缺的部分,为整个芯片提供精确的电压参考点............

qq_50968231的博客 5万+

一文搞懂 this、apply、call、bind

一文搞懂 this、apply、call、bind

whl0071的专栏 402

转录组数据提取技巧汇总

数据整理是数据分析的前提,而数据的正确提取则是数据整理的前提。

zfyyzhys的博客 1781

二、基于C语言的JPEG解码代码详解

// JPEG解码 // 输入JPEG后输出Bitmap #include <stdio.h> #include <stdlib.h> #pragma warning(disable : 4996) unsigned int BuffIndex; // JPEG数据的位置 unsigned int BuffSize; // JPEG数据的大小 unsigned int BuffX; // 图像的横向尺寸 unsigned int BuffY; //

m0_37633745的博客 4451

this指向问题call、apply、bind超详细

例子中,obj的A/B函数都是返回一个内部定义的函数,A、B内部定义的函数函数返回值都是this,只是在A中,内部函数是箭头函数,而B中则是普通函数。将A、B函数创建的内部函数分别赋值给变量func进行调用,未指定调用者,可以发现箭头函数的返回值this能够指向obj,而普通函数的this则因为未指定调用者而指向了全局对象。箭头函数的this取决于函数定义所在的上下文中this,即函数定义外部this是什么,箭头函数内部的this就是什么,相当于固化了当前执行环境中的this,注意不是函数定义所在的对象!

weixin_52901235的博客 848

citespace基本操作

聚类分析 时间线图 这些结果都是高被引文献的相关呈现结果,代表该领域的文献基础 下面可以看看该project的前沿领域 选择keywords 和term go! 调整显示方式 生成凸线图:表示 在某个研究领域或者时间段内 ,大家对某个领域或者某个词的关注度突然增高,凸显前沿方向的转变 以此来发现热点 ...

生信小博士的博客 1万+

【THE LAST TIME】this:call、apply、bind

前言 The last time, I have learned【THE LAST TIME】一直是我想写的一个系列,旨在厚积薄发,重温前端。也是给自己的查缺补漏和技术分...

全栈前端精选 376

卫朋:IPD流程落地——产品计划阶段拆解

IPD计划阶段拆解

产品线负责人 954

【GameFramework框架内置模块】9、有限状态机(FSM)

这篇文章分享FSM有限状态机,了解过StarForce源码的同学相比都比较了解,GameFramework框架给我们抽象了一个Procedure流程的概念。这个Procedure流程可以方便的处理我们游戏从启动到游戏的各个流程阶段的处理逻辑,实现的核心就是FSM状态机,内部的Procedure流程就是不同的FsmState状态。接下来,就是FSM有限状态机的教程了。有限状态机(Finite-state machine,FSM)

优快云博客专家,Unity3D高级软件工程师,《Unity 3D从入门到实战》作者。 2530

深入解析 JS 中的 this、call、apply 和 bind

call、apply 和 bind都可以改变函数的this对象指向call、apply 和 bind第一个参数都是this要指向的对象,如果如果没有这个参数或参数为undefined或null,则默认指向全局windowcall、apply 和 bind都可以传参,但是apply是数组,而call是参数列表,且apply和call是一次性传入参数,而bind可以分为多次传入bind是返回绑定this之后的函数,applycall则是立即执行。

qq_39279448的博客 1084

使用安卓的IMU数据进行 行人航位推算(PDR)推算步长 附python 代码

加速度计数据、陀螺仪数据、重力传感器数据、姿态仰角数据。数据分析与定位轨迹生成主要使用Python离线完成。示意图。

三维点云技术探索 1912

改变this指向,call,apply,bind的不同

改变this指向,call,apply,bind的不同

前端小白的逆袭 3097

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

this和apply、call、bind

JavaScript 的 this 总是指向一个对象,而具体指向哪个对象是在运行时基于函数的执行环境动态绑定的。 this的使用场景 1. 普通函数调用 const name = "oliver"; function getName(){ alert ( this === window ); // 输出:true alert ( this.name ) //输出: oliver } getName(); /* 当函数不作为对象的属性被调用时,也就是普通函数方式,此时的 this 总是指 向全局对象。.

断桥铲雪的博客 301

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

call、apply、bind区别及this的指向

call、apply、bind比较: 首先call和apply都是用于调用函数,第一个参数作为函数内this的值。他俩的唯一区别就在于从第二个参数开始,call接收的将参数依次传递进去并用逗号分隔;而apply接收的是将这些参数放进数组里面,以一个参数数组传递。 bind用来创建一个新的函数,不会立刻执行,将一个值绑定到函数的this上,并将绑定好的函数返回。 三者比较: apply 、...

reaaal的博客 409

深度学习工具包 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中 固定 this指向 (call、apply、bind 函数)

由于对象的属性可以赋给另一个对象,所以属性所在的当前对象是可变的,即this的指向是可变的。 this的动态切换,固然为 JavaScript 创造了巨大的灵活性,但也使得编程变得困难和模糊。 有时,需要把this固定下来,避免出现意想不到的情况

qq_36647492的博客 1221

Bind & Call & Apply(改变this指向)

Bind & Call & Apply(改变this指向) Bind/call/apply三个方法都是可以改变对应函数的this指向的, bind方法通过该函数调用并且返回一个新的函数, 新的函数已经修改了this指向,只有调用这个新的函数,函数体才会被执行。 (会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数) 而call/apply方法是会直接绑定this并进行调用的, 调用的时候,函数内

SeriousLose 1600

this以及apply,call,bind之间的区别

关于this对象this对象是在运行时基于函数的执行环境绑定的:在全局环境中,this等于window,而当函数被作为某个对象的方法调用时,this等于那个对象。不过,匿名函数的执行环境具有全局性,因此其this对象通常指向window。------《Javascript高级程序设计》除了书里的解释,再来几个直白的例子:// 定义一个全局变量var type = "全局"; // 定义函数aafu...

我在长安长安 3786

this指向和apply,call,bind三者的区别

一、前言 this指向,apply,call,bind的区别是一个经典的面试问题,同时在项目中会经常使用到的原生的js方法。同时也是ES5中的众多坑的一个。ES6中可能会极大的避免了this产生的错误,有时候需要维护老的项目还是有必要了解一下this的指向和apply,call,bind三者的区别。 二、this的指向 在ES5中,其实this的指向,始终坚持一个原理:this永远指向...

weixin_30871905的博客 92

【JavaScript】this、call、apply、bind

call()和apply()都是函数对象的方法,需要通过函数对象来调用,这两个方法都可以将一个对象指定为第一个参数,此时这个对象将成为函数执行时的this。call()方法可以将实参在对象之后依次传递,apply()方法需要将实参封装在一个数组中进行传递 fun.call(obj, 1, 2); fun.apply(obj, [1, 2]); arguments 是一个类数组对象,在调用函...

公众号:前端充电宝 557

彻底弄清 this call apply bind 以及原生实现

转自:彻底弄清 this call apply bind 以及原生实现 有关 JS 中的 this、call、apply 和 bind 的概念网络上已经有很多文章讲解了 这篇文章目的是梳理一下这几个概念的知识点以及阐述如何用原生 JS 去实现这几个功能 this 指向问题 this this 的指向在严格模式和非严格模式下有所不同;this 究竟指向什么是,在绝大多数情况下取决于函数如何被...

xiaojing的博客 280

this apply call bind

this apply call bindapply callapply call 的区别bindapply call bind 的比较总结 apply call 在 javascript 中,call 和 apply 都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部 this 的指向。 JavaScript 的一大特点是,函数存在「定义时上下文」和「运...

不能再菜 487

js this 指向 call apply bind

箭头函数没有自己的this 所以bind 方法无效 内部this都指向外部的this 函数体内 this 对象 就是定义时所在对象 而不是使用时所在对象 (function() { return [(() => this.x).bind({x: 'inner'})()]; }).call({x: 'outer'}) // ['outer'] ...

weixin_43069018的博客 177
上一篇: v3签名key和v2还有v1有什么区别
下一篇: 回流与重绘
JerryQuary
博客等级 码龄9年 24粉丝 20原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值