V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
coolicer
V2EX  ›  JavaScript

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

  •  
  •   coolicer · 2013-07-05 10:35:53 +08:00 · 3617 次点击
    这是一个创建于 3941 天前的主题,其中的信息可能已经有所发展或是发生改变。
    这2个东西用起来不是很熟练,有没有什么好方法。我知道这是改变context的函数,但是用起来总是很不灵活。

    其实我心中还是有概念的,不就是改变执行环境的this....
    5 条回复    1970-01-01 08:00:00 +08:00
    wencheng
        1
    wencheng  
       2013-07-05 11:55:57 +08:00
    这个没什么不方便吧,觉得你可能对context的理解不够深吧,慢慢来不用一下要把call和apply用的那么精。
    qiqiboy
        2
    qiqiboy  
       2013-07-05 12:24:40 +08:00
    现在不理解就避免使用丫,看的代码多了总有一天会顿悟的
    kfll
        3
    kfll  
       2013-07-05 14:08:40 +08:00
    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  
       2013-07-05 14:38:35 +08:00
    经典用法,可以帮助理解

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

    2、判断数据类型
    {}.toString.call([1, 2, 3]) //=> [object Array]
    coolicer
        5
    coolicer  
    OP
       2013-07-05 15:32:43 +08:00
    @kfll [Node.addClass, Node.removeClass][!!condition * 1].call(nodeExample, 'eg') 妙啊。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5477 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 03:04 · PVG 11:04 · LAX 20:04 · JFK 23:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.