V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
coolicer

SB前端求解答,我的call和apply。

  •  
  •   coolicer · Jul 5, 2013 · 4618 views
    This topic created in 4679 days ago, the information mentioned may be changed or developed.
    这2个东西用起来不是很熟练,有没有什么好方法。我知道这是改变context的函数,但是用起来总是很不灵活。

    其实我心中还是有概念的,不就是改变执行环境的this....
    5 replies    1970-01-01 08:00:00 +08:00
    wencheng
        1
    wencheng  
       Jul 5, 2013
    这个没什么不方便吧,觉得你可能对context的理解不够深吧,慢慢来不用一下要把call和apply用的那么精。
    qiqiboy
        2
    qiqiboy  
       Jul 5, 2013
    现在不理解就避免使用丫,看的代码多了总有一天会顿悟的
    kfll
        3
    kfll  
       Jul 5, 2013
    if (condition)
    nodeExample.removeClass('eg')
    else
    nodeExample.addClass('eg')

    ==>

    [Node.addClass, Node.removeClass][!!condition * 1].call(nodeExample, 'eg')

    ----------------

    当然,第一种要容易明白的多...

    ----------------

    Object.prototype.toString.call(arrExample)
    Array.prototype.forEach.call('hello', function(char, i) { console.log(char + '_') })

    ----------------
    tulike1
        4
    tulike1  
       Jul 5, 2013
    经典用法,可以帮助理解

    1、求数组的最大值
    Math.max.apply(Math, [1, 2, 3, 4, 5]) //=> 5

    2、判断数据类型
    {}.toString.call([1, 2, 3]) //=> [object Array]
    coolicer
        5
    coolicer  
    OP
       Jul 5, 2013
    @kfll [Node.addClass, Node.removeClass][!!condition * 1].call(nodeExample, 'eg') 妙啊。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   979 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 20:44 · PVG 04:44 · LAX 13:44 · JFK 16:44
    ♥ Do have faith in what you're doing.