关于$.when(),$.apply(),$.when.apply(),$.when.apply().then()的用法(项目总结)

本文详细介绍了jQuery中的$.when()方法用于处理一个或多个对象的回调函数,以及$.apply()方法在对象继承和提升程序性能方面的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中有这样的应用,以前基本上没有用到过$.when(), $.apply()这些方法,所以就自己百度了一下

$.when()

jQuery.when() 方法

jQuery 杂项方法jQuery 杂项方法

实例

一个参数传递给 $.when() 被受理,执行回调函数

$ ( function ( ) { $. when ( { testing : 123 } ) . done ( function ( x ) { alert ( x . testing ) ; } /* alerts "123" */ ) ; } )

尝试一下 »

定义和用法

$.when() 函数提供一种方法来执行一个或多个对象的回调函数。

提示:如果向 jQuery.when 传入一个延迟对象,那么会返回它的 Promise 对象(延迟方法的一个子集)。 可以继续绑定 Promise 对象的其它方法,例如, defered.then 。当延迟对象已经被受理(resolved) 或被拒绝(rejected)(通常是由创建延迟对象的最初代码执行的),那么就会调用相应的回调函数。


语法

$.when( deferreds )

参数 描述
deferreds Deferred类型 一个或多个延迟对象,或者普通的JavaScript对象


实例

更多实例


如果你不传递任何参数,jQuery.when()将返回一个resolved(受理)状态的 promise 对象。

实例

不传递任何参数,执行回调函数

[mycode3 type="javascript"] $(function () { $.when().then(function( x ) { alert( "I fired immediately" ); }); }) [/mycode3]

尝试一下 »

在多个延迟对象传递给jQuery.when() 的情况下,该方法返回一个新的"宿主"延迟对象,当所有的延迟对 象被受理(resolve)时,该方法才会受理它的宿主延迟对象。当其中有一个延迟对象被拒绝(rejected)时, 该方法就会拒绝它的宿主延迟对象。当宿主对象被受理时,doneCallbacks(受理回调)将被执行。

实例

传入多个延迟对象

[mycode3 type="javascript"] $(function () { var d1 = $.Deferred(); var d2 = $.Deferred(); $.when( d1, d2 ).done(function ( v1, v2 ) { alert( v1 ); // "Fish" alert( v2 ); // "Pizza" }); d1.resolve( "Fish" ); d2.resolve( "Pizza" ); }) [/mycode3]

尝试一下 »

如果没有值传递给延迟对象的受理(resolved)事件,那么相应的doneCallback参数 将是undefined。 如果传递给延迟对象的受理(resolved)事件为单个的值, 相应的参数 将保留那个值。 在传递给延迟对象的解决(resolved)事件为为多个值的情况下, 相应的 参数将是这些值组成的数组。

实例

传入多个不同类型的延迟对象

[mycode3 type="javascript"] $(function () { var d1 = $.Deferred(); var d2 = $.Deferred(); var d3 = $.Deferred(); $.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) { alert( v1 ); // v1 is undefined alert( v2 ); // v2 is "abc" alert( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ] }); d1.resolve(); d2.resolve( "abc" ); d3.resolve( 1, 2, 3, 4, 5 ); }) [/mycode3]

尝试一下 »

在多个延迟的情况下,如果延迟对象之一被拒绝(rejected),jQuery.when()触发立即 调用 "宿主" 延迟对象的 failCallbacks 回调函数。

实例

多个延迟对象之一被拒绝时调用failCallbacks 回调函数

[mycode3 type="javascript"] $(function () { $.when($.ajax("/page1.php"), $.ajax("/page2.php")).then(function(data, textStatus, jqXHR){ alert(jqXHR.status); }, function(obj){ alert(obj.statusText); }); }) [/mycode3]

尝试一下 »
$.apply()


js中apply方法的使用

1、对象的继承,一般的做法是复制:Object.extend

prototype.js的实现方式是:

 

 Object.extend = function(destination, source) { 
    for (property in source) { 
        destination[property] = source[property]; 
    } 
    return destination; 
}

 

除此之外,还有种方法,就是:Function.apply(当然使用Function.call也是可以的)

apply方法能劫持另外一个对象的方法,继承另外一个对象的属性

Function.apply(obj,args)方法能接收两个参数

    obj:这个对象将代替Function类里this对象

    args:这个是数组,它将作为参数传给Function(args-->arguments)

apply示范代码如下:

 

<script> 
function Person(name,age){   //定义一个类,人类  
    this.name=name;     //名字  
    this.age=age;       //年龄 
    this.sayhello=function(){alert("hello")};

function Print(){            //显示类的属性 
    this.funcName="Print"; 
    this.show=function(){      
        var msg=[];
        for(var key in this){ 
            if(typeof(this[key])!="function"){
                msg.push([key,":",this[key]].join(""));
            }
        } 
        alert(msg.join(" "));
    };

function Student(name,age,grade,school){    //学生类 
    Person.apply(this,arguments);
    Print.apply(this,arguments);
    this.grade=grade;                //年级 
    this.school=school;                 //学校 

var p1=new Person("jake",10);
p1.sayhello();
var s1=new Student("tom",13,6,"清华小学");
s1.show();
s1.sayhello();
alert(s1.funcName);
</script>

 

学生类本来不具备任何方法,但是在Person.apply(this,arguments)后,

他就具备了Person类的sayhello方法和所有属性。

在Print.apply(this,arguments)后就自动得到了show()方法

 

2、利用Apply的参数数组化来提高

Function.apply()在提升程序性能方面的技巧

我们先从Math.max()函数说起,Math.max后面可以接任意个参数,最后返回所有参数中的最大值。

比如 
alert(Math.max(5,8))   //8
alert(Math.max(5,7,9,3,1,6))   //9

但是在很多情况下,我们需要找出数组中最大的元素。
var arr=[5,7,9,1]
alert(Math.max(arr))    // 这样却是不行的。一定要这样写

function getMax(arr){
    var arrLen=arr.length;
    for(var i=0,ret=arr[0];i<arrLen;i++){
        ret=Math.max(ret,arr[i]);       
    }
    return ret;
}

这样写麻烦而且低效。如果用 apply呢,看代码:
function getMax2(arr){
    return Math.max.apply(null,arr);
}
两段代码达到了同样的目的,但是getMax2却优雅,高效,简洁得多。

 

再比如数组的push方法。
var arr1=[1,3,4];
var arr2=[3,4,5];
如果我们要把 arr2展开,然后一个一个追加到arr1中去,最后让arr1=[1,3,4,3,4,5]
arr1.push(arr2)显然是不行的。 因为这样做会得到[1,3,4,[3,4,5]]

我们只能用一个循环去一个一个的push(当然也可以用arr1.concat(arr2),但是concat方法并不改变arr1本身)
var arrLen=arr2.length
for(var i=0;i<arrLen;i++){
    arr1.push(arr2[i]);
}

自从有了Apply,事情就变得如此简单
Array.prototype.push.apply(arr1,arr2)

HomePage.prototype.show = function () {
    var me = this;
    var defs = [];
    defs.push(me.getWeather());
    //banner
    var mySwiper = new Swiper('.swiper-container', {
        loop: true,
        autoplay: 3000,
        pagination: '.swiper-pagination'
    });
    me.clearList();
    defs.push(me.renderPage());
    $.when.apply(this, defs).then(function () {
        console.log($(this));
        // 绑定刷新加载事件
        setTimeout(function () {
            me.bindLoadEvents_();
        }, 500);
    });
};

在这里呢$.when(ajax1,ajax2,ajax3,ajax4,ajax5).then()  等它向后台发送请求ajax1,ajax2,ajax3,ajax4,ajax5等这五个请求都发送出去并都返回数据后执行then(),于是就要apply(),为什么呢,因为ajax1,ajax2,ajax3,ajax4,ajax5这些都太多了,有可能还不止五个,如果都写在一起,太麻烦了,于是就有了apply的应用,$.when.apply(this,defs)在这里使用apply是因为defs是一个数组,使用apply是因为展开数组defs后,再执行$.when,这样就避免了把那么多请求或者函数写在一个括号里。

同时$.when.apply(this,defs)这里面的this是指HomePage,其实这里的this可以是其他值,主要是在then里面用到了this,如果没用到的话,this也可以写为null,也就是$.when.apply(null,defs)或者$.when.apply(‘aaaa’,defs)。看来我理解的还是有些片面的,为什么呢?因为在这里我把apply的用法过于片面了,$.when.apply(this,defs),首先apply在这里是先调用,也就是this这个方法调用$.when()这个方法,然后就是defs只是this在使用$.when()这个方法时,往里面传的参数而已,其实在这里apply也可以换成call,只不过defs这些参数不能用数组表示了,而是写在$.when.call()里面用,隔开,所以这里为了方面就使用了,


隔开  在Activity.call(this);这个方法就相当于调用了Activity();只不过,在调用这个Activity()这个方法的时候,把Activity函数中的this换成了HomePage而已。不过对于更深的理解我还需要进一步查阅资料,再进行总结。

In machine learning, `tape` refers to the automatic differentiation engine in TensorFlow. When a `Tensor` loss is passed, the `tape` records all the operations that are performed on the input `Tensor` and calculates gradients with respect to the trainable variables. These gradients are then used to update the weights of the model during training. To use `tape`, you typically write your training loop inside a `tf.GradientTape()` context. For example: ``` import tensorflow as tf # Define the model model = tf.keras.Sequential([...]) # Define the loss function loss_fn = tf.keras.losses.MeanSquaredError() # Define the optimizer optimizer = tf.keras.optimizers.Adam() # Define the inputs and targets inputs = tf.constant([...]) targets = tf.constant([...]) # Start the training loop for epoch in range(num_epochs): with tf.GradientTape() as tape: # Forward pass predictions = model(inputs) # Compute the loss loss = loss_fn(targets, predictions) # Compute the gradients gradients = tape.gradient(loss, model.trainable_variables) # Update the weights optimizer.apply_gradients(zip(gradients, model.trainable_variables)) ``` In this example, the `tape` records the operations inside the `with tf.GradientTape()` context, which include the forward pass through the model and the computation of the loss. Then, the gradients are computed with respect to the trainable variables (i.e., the weights of the model) using `tape.gradient()`. Finally, the weights are updated using the computed gradients with `optimizer.apply_gradients()`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值