CoffeeScript扩展运算符修改'this'?

时间:2012-02-22 15:29:28

标签: ruby coffeescript this prototype extend

我最近偶然发现了什么。我想添加从数组中删除对象的功能:

someArray.remove(element)

我想使用CoffeeScript的extend运算符,并执行以下操作:

Array::remove = (element) ->
  return false unless _.include(this, element)
  this = this.splice(_.indexOf(this, element), 1)
  true

但是创建的原型函数将this指向Array对象本身,所以唯一的方法是返回一些东西,如下所示:

someArray = someArray.remove(element)

和这样的实现:

Array::remove = (element) ->
  return this unless _.include(this, element)
  this.splice(_.indexOf(this, element), 1)

在红宝石中,这是joinjoin!之间的确切差异。

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:2)

我认为你误解了splice。它在阵列本身上运行。这似乎可以解决问题,除非我完全误解了你的问题:

_ = require "underscore"

Array::remove = (element) ->
  index = _.indexOf @, element
  return false if index is -1
  @splice index, 1
  true

foo = ["a", "b", "c"]
console.log foo            # => ['a', 'b', 'c']
console.log foo.remove "b" # => true
console.log foo            # => ['a', 'c']
console.log foo.remove "d" # => false
console.log foo            # => ['a', 'c']

请注意,coffeescript包含indexOf的垫片,因此不严格需要下划线,所以你可以这样做:

Array::remove = (element) ->
  index = @indexOf element
  return false if index is -1
  @splice index, 1
  true

答案 1 :(得分:1)

我将其实现为:

Array::remove = (element) ->
  return false unless element in @
  @splice(@indexOf(element), 1)
  true

这很好用。我不确定您使用this变量遇到了什么问题,但您应该注意splice更改了原始数组,因此无需进行分配。你的第一个实现甚至都没有为我编译,因为CoffeeScript不允许你分配给this