元编程:内省(xǐng)

Ruby code:

class Greeting
  def initialize text
    @text = text
  end

  def welcome
    @text
  end
end

my_object = Greeting.new "Hello"

puts my_object.welcome
puts
puts my_object.class
puts
puts my_object.class.instance_methods false
puts
puts my_object.instance_variables

ECMAScript/JavaScript Code:

"use strict";

class Greeting {
  constructor(text) {
    this.text = text;
  }
  welcome() {
    return this.text;
  }
}
var my_object = new Greeting("Hello");
console.log(my_object.welcome());
console.log('');
console.log(my_object.constructor);
console.log('');
for (var m in my_object) {
  console.log(m);
}
console.log('');
console.log(my_object);

CoffeeScript code:

class Greeting
  constructor: (text) ->
    @text = text

  welcome: ->
    @text

my_object = new Greeting "Hello"

console.log my_object.welcome()
console.log ''
console.log my_object.constructor
console.log ''
console.log m for m of my_object
console.log ''
console.log my_object
Comments
Write a Comment