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


source to share





All Articles