Wednesday 15 July 2015

What are the differences between 'self' in ruby and 'this' in javascript -



What are the differences between 'self' in ruby and 'this' in javascript -

i familiar ruby , begin larn javascript. safe skip larn 'this' , consider finish equivalence of ruby's 'self' in javascript , 'apply' in javascript same 'instance_eval' in ruby?

if not,what big differences between them?

self used in ruby metaprogramming.

from metaprogramming ruby book:

every line of ruby code executed within object—the so–called current object. current object known self, because can access self keyword.

only 1 object can take role of self @ given time, no object holds role long time. in particular, when phone call method, receiver becomes self. moment on, instance variables instance variables of self, , methods called without explicit receiver called on self. code explicitly calls method on other object, other object becomes self.

for example:

class foo attr_reader :name def initialize(name) @name = name end # here self indicates class foo def self.bar end # here self indicates instance of class foo def baz self.name end end

now:

foo = foo.new('foobar') foo.baz #=> 'foobar'

while in javascript utilize of this keyword powerful , unique, not refer object(as of es5's strict mode) ruby shown above. this can have value. value of this within given function phone call determined how function called (not function defined, i.e. context, in languages ruby, c#, or java). but, similar ruby's self, this can't set assignment during execution. example:

global context(directly copied here):

console.log(this.document === document); // true // in web browsers, window object global object: console.log(this === window); // true this.a = 37; console.log(window.a); // 37

or object method:

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

from examples shown it's pretty clear javascript's this isn't cousin brother of ruby's self, have little pinch of similarity in behaviors.

for exploring ruby's self farther read this , javascript's this read this.

javascript ruby

No comments:

Post a Comment