What is the difference between a Ruby public class and a JavaScript prototype object?

In Ruby, you can use openclass to add the following properties:

class String
   attr_accessor :ruby
   def open
      ruby = 'open'
   end
   def close
      ruby = 'close'
   end
end

      

Then you can use

x = String.new
x.open # it will set ruby to 'open'
'open'
x.close # it will set ruby to 'close'
'close'

      

In JavaScript, you can use a prototype to add properties like this:

String.prototype.ruby = {}
String.prototype.open = function () { this.ruby = "open"; }
String.prototype.close = function () { this.ruby = "close"; }

      

Then you can call these prototypes like:

var x = new String()
console.log(['ruby', x.ruby].join(':'))
/* when invoke open */
x.open()
console.log(['ruby', x.ruby].join(':'))
/* when invoke close */
x.close()
console.log(['ruby', x.ruby].join(':'))

      

It is the same?

+3
javascript ruby


source to share


No one has answered this question yet

Check out similar questions:

7287
What does "use strict" do in JavaScript, and what are the reasons for it?
5722
How can I remove a property from a JavaScript object?
5101
What's the most efficient way to deeply clone an object in JavaScript?
4086
What's the difference between using "let" and "var"?
3714
How to check if an array contains a value in JavaScript?
2984
What is the difference between calling and submitting an application?
2743
What is it!! (not) operator in JavaScript?
2256
Set default parameter value for JavaScript function
2201
How do you decide when to use Node.js?
1949
How does JavaScript.prototype work?



All Articles
Loading...
X
Show
Funny
Dev
Pics