gpt4 book ai didi

javascript - ruby中的 'self'和javascript中的 'this'有什么区别

转载 作者:数据小太阳 更新时间:2023-10-29 07:16:53 24 4
gpt4 key购买 nike

熟悉ruby,开始学习javascript。跳过学习“this”并将其视为 ruby​​ 中 javascript 中的“self”和 javascript 中的“apply”与 ruby​​ 中的“instance_eval”完全等价是安全的吗?

如果不是,它们之间有什么大的区别?

最佳答案

self 广泛用于 Ruby Metaprogramming .

来自 Metaprogramming Ruby书:

Every line of Ruby code is executed inside an object—the so–called current object. The current object is also known as self, because you can access it with the self keyword.

Only one object can take the role of self at a given time, but no object holds that role for a long time. In particular, when you call a method, the receiver becomes self. From that moment on, all instance variables are instance variables of self, and all methods called without an explicit receiver are called on self. As soon as your code explicitly calls a method on some other object, that other object becomes self.

例如:

class Foo

attr_reader :name

def initialize(name)
@name = name
end

# here self indicates the class itself Foo
def self.bar
end

# here self indicates the instance of class Foo
def baz
self.name
end
end

现在:

foo = Foo.new('FooBar')
foo.baz #=> 'FooBar'

在 JavaScript 中使用 this关键字是强大而独特的,它不像上面所示的 Ruby 那样引用对象(在 ES5 的严格模式下)。 this 可以有任何值。任何给定函数调用中 this 的值取决于函数的调用方式(而不是定义函数的位置,即上下文,如 Ruby、C# 或 Java 等语言)。但是,类似于Ruby 的selfthis 不能在执行过程中通过赋值来设置。例如:

全局上下文(directly copied from here):

console.log(this.document === document); // true

// In web browsers, the window object is also the global object:
console.log(this === window); // true

this.a = 37;
console.log(window.a); // 37

或者作为一个对象方法:

var foo = {};
foo.bar = function() {
console.log(this.firstName);
};
foo.firstName = 'FooBar';
foo.bar(); // "FooBar"

从显示的示例中可以很清楚地看出,JavaScript 的 this 与 Ruby 的 self 并不完全是堂兄弟,但它们在行为上有一点点相似之处。

进一步探索 Ruby 的 self read this对于 JavaScript 的 this read this .

关于javascript - ruby中的 'self'和javascript中的 'this'有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26717596/

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