在Ruby中,你可以使用openclass添加一些这样的属性:
class String
attr_accessor :ruby
def open
ruby = 'open'
end
def close
ruby = 'close'
end
end
然后你可以使用
x = String.new
x.open # it will set ruby to 'open'
'open'
x.close # it will set ruby to 'close'
'close'
在JavaScript中,您可以使用prototype来添加如下属性:
String.prototype.ruby = {}
String.prototype.open = function () { this.ruby = "open"; }
String.prototype.close = function () { this.ruby = "close"; }
然后你可以像这样调用这些原型方法:
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(':'))
它们是一样的吗?