ruby与javascript面向对象编程的比较

原文:http://howtonode.org/object-graphs-3作者分析了ruby与javascript两者在面向对象模式的区别,这里只摘取重点部分,有兴趣的读者可看原文。Ruby先来看一个简单的字符串:

animal = "cat"

引用Notice that every object has a class. Our string is of class String which inherits from the class Object. It’s class String is of class Class which inherits Module and then Object.再来看JavaScript

var animal = "cat";

引用Remember that you can simulate classes in JavaScript using constructor + prototype pairs. That’s just what the built-in object types do. The prototypes are objects and thus inherit directly from Object.prototype and the constructors are functions and inherit from Function.prototype.对象私有方法,注意这里说的是对象,而不是类。类的私有方法在类的声明中用private修饰。而对象私有方法是指一个对象的方法相对同类的其它对象是私有的。如下代码:

animal = "cat" #animal对象已被创建def animal.speak #在animal对象已被创建后,可赋于其新的方法,该方法不能被同类的其它对象共享,所以是私有的  puts "The #{self} says miaow"endanimal.speakputs animal.upcase

引用Notice that it injected a new anonymous class directly in front of the object and put the new method there for you. This class is hidden though. If you call the animal.class() then you’ll get a reference to String directly.来看javascript

var animal = /cat/;animal.speak = function speak() {  console.log("The " + this + " says miaow");};animal.speak();animal.test('caterpiller');

可以看到实现方式与 ruby相类似。定义类Ruby

class Daveend

Javascript

function Dave() {}

类方法ruby

# Make a parent classclass Person  # with an instance method  def greet    puts "Hello"  end  # and a class method.  def self.create    self.new  endend# Create a subclassclass Dave < Personend# and test it.puts Dave.createputs Dave.newDave.create.greet

引用You see that it inserted a new anonymous class in the chain to store the create methodjavascript

// Make a parent classfunction Person() {}// with an instance methodPerson.prototype.greet = function greet() {  console.log("Hello");}// and a class method.Person.create = function create() {  return new this();};// Create a subclassfunction Dave() {}Dave.__proto__ = Person;Dave.prototype.__proto__ = Person.prototype;// and test it.console.log(Dave.create());console.log(new Dave);Dave.create().greet();

引用Here we make the constructor inherit from it’s parent constructor (so that “class methods” get inherited) and inherit the prototypes so that “instance methods” get inherited. Again there is no need for hidden classes since javascript allows storing function properties on any object.痛苦留给的一切,请细加回味!苦难一经过去,苦难就变为甘美。

ruby与javascript面向对象编程的比较

相关文章:

你感兴趣的文章:

标签云: