在lua中模拟javascript` this`行为

Eri*_*ric 4 javascript lua

我总是喜欢在Javascript中通过这样做来设置this指针的值的方式f.call(newThisPtrValue).我在lua写了一些东西来做这件事,它起作用:

_G.call = function(f, self, ...)
    local env = getfenv(f)
    setfenv(f, setmetatable({self = self}, {__index = env}))
    local result = {f(...)}
    setfenv(f, env)
    return unpack(result)
end
Run Code Online (Sandbox Code Playgroud)

有几点我不确定:

  1. 我希望有一个性能开销unpack({...}).有没有解决的办法?
  2. 这有可能以任何方式严重破坏功能的环境吗?
  3. 这是一个真的不好的想法吗?

Phr*_*ogz 6

Lua的伪OOP的一个很好的好处是它已经非常容易实现:

local Person = {}
function Person:create( firstName, lastName )
  local person = { firstName=firstName, lastName=lastName }
  setmetatable(person,{__index=self})
  return person
end
function Person:getFullName()
  return self.firstName .. " " .. self.lastName
end
local me  = Person:create( "Gavin", "Kistner" )
local you = Person:create( "Eric", "Someone" )
print( me:getFullName() )
--> "Gavin Kistner"
print( me.getFullName( you ) )
--> "Eric Someone"
Run Code Online (Sandbox Code Playgroud)

我写了一篇文章讨论这个(以及其他内容):
学习Lua:伪OOP语法和范围.

编辑:这是一个像jQuery的继续例子each:

local Array = {}
function Array:new(...)
  local a = {...}
  setmetatable(a,{__index=self})
  return a
end
function Array:each(callback)
  for i=1,#self do
    callback(self[i],i,self[i])
  end
end
function Array:map(callback)
  local result = Array:new()
  for i=1,#self do
    result[i] = callback(self[i],i,self[i])
  end
  return result
end
function Array:join(str)
  return table.concat(self,str)
end

local people = Array:new( me, you )

people:each( function(self,i)
  print(self:getFullName())
end )
--> "Gavin Kistner"
--> "Eric Someone"

print( people:map(Person.getFullName):join(":") )
--> "Gavin Kistner:Eric Someone"
Run Code Online (Sandbox Code Playgroud)