gpt4 book ai didi

ruby - 方法闭包似乎在 therubyracer 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 16:30:32 27 4
gpt4 key购买 nike

一旦我将一个方法存储在 V8::Context 中,该方法的所有后续实例都以任何名称存储在任何上下文中,其行为与初始实例一样(即,就好像原始实例已再次存储一样)。

我尝试通过以下方式隔离/演示问题:

require 'V8'

class TestClass
def test_method
self.inspect
end
end

(1..2).each do |cxt_i|
cxt = V8::Context.new
[:test_method, :test_method2].each_with_index do |method_name, method_i|
method = TestClass.new.method(:test_method)
cxt[method_name.to_s] = method
script = method_name.to_s+'()'
puts "Context #{cxt_i}, method #{method_i+1} result is #{method.call}, V8 returns #{cxt.eval(script)}"
end
end

产生以下输出:

Context 1, method 1 result is #<TestClass:0x007fce2419cdb0>, V8 returns #<TestClass:0x007fce2419cdb0>
Context 1, method 2 result is #<TestClass:0x007fce2419b780>, V8 returns #<TestClass:0x007fce2419cdb0>
Context 2, method 1 result is #<TestClass:0x007fce2419abc8>, V8 returns #<TestClass:0x007fce2419cdb0>
Context 2, method 2 result is #<TestClass:0x007fce24199a98>, V8 returns #<TestClass:0x007fce2419cdb0>

最佳答案

这是一个弱引用问题。通过在内循环中插入 GC.start,我们强制对 V8 上下文中的弱引用进行垃圾回收。但是会大大减慢速度。

require 'v8'

class TestClass
def test_method
self.inspect
end
end

(1..2).each do |cxt_i|
cxt = V8::Context.new
[:test_method, :test_method2].each_with_index do |method_name, method_i|
method = TestClass.new.method(:test_method)
cxt[method_name.to_s] = method
script = method_name.to_s+'()'
puts "Context #{cxt_i}, method #{method_i+1} result is #{method.call}, V8 returns #{cxt.eval(script)}"
GC.start # <<<<=========
end
end

输出:

Context 1, method 1 result is #<TestClass:0x007f8f13a26cd8>, V8 returns #<TestClass:0x007f8f13a26cd8>
Context 1, method 2 result is #<TestClass:0x007f8f135cca48>, V8 returns #<TestClass:0x007f8f135cca48>
Context 2, method 1 result is #<TestClass:0x007f8f135ceac8>, V8 returns #<TestClass:0x007f8f135ceac8>
Context 2, method 2 result is #<TestClass:0x007f8f135cdbf0>, V8 returns #<TestClass:0x007f8f135cdbf0>

ruby -v 是 ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-linux],libv8 是 3.11.8.17 x86_64-linux/p>

关于ruby - 方法闭包似乎在 therubyracer 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16847402/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com