Showing posts with label Methods. Show all posts
Showing posts with label Methods. Show all posts

Tuesday, March 11, 2008

Relationship of Object and Kernel

# Object mixes in the Kernel module, making the built-in kernel functions globally accessible. The instance methods of Object are defined by the Kernel module.


p Kernel.instance_methods(false).length # 42 # Object instance methods
p Kernel.methods(false).length # 65 # Kernel module methods
p Module.instance_methods(false).length # 34 # Module instance methods, Kernel module is instance of Module class.
p Kernel.methods.length # 134

kernel_instance_methods = Kernel.instance_methods(false)
kernel_module_methods = Kernel.methods(false)
module_instance_methods = Module.instance_methods(false)

kernel_methods = [] # 134

Kernel Module include module methods(such as puts/p/gsub...) and module instance methods(such as __id__/__send__/id/send/object_id...), Object class has not defined instance methods, its instance methods are mixed in from Kernel module.

Kernel.methods include three group methods: object instance methods and Kernel module methods and instance methods of class Module.
class A
def self.method1
self.name
end
end
p A.method1
# A
p A.methods(false)
# ["method1"]

Monday, January 21, 2008

keywords of this in javascript methods

<html>
<head>
<title> cloures </title>
<script src="/lib/prototype/prototype.js" type="text/javascript"></script>

<script type="text/javascript">
var o = {};
var obj = {
name: 'A nice demo in obj',
fx: function() {
return this.name + " " + $A(arguments).join(', ');
},
rf: function() {
return function() { return this.name + " " + $A(arguments).join(', '); }
}
};
alert(obj.fx);
window.name = 'I am such a beautiful window!';
function runFx(f) {
return f();
}
var fx2 = obj.fx.bind(obj, 'otherArg1', 'otherArg2');
var rf2 = obj.rf.bind(obj, 'otherArg1', 'otherArg2');
alert(fx2);
document.write(runFx(obj.fx));
document.write("<br />");
document.write(runFx(fx2));
document.write("<br />");
document.write(obj.rf()());
document.write("<br />");
document.write(rf2()());
document.write("<br />");
</script>
</head>
<body>
Javascript的闭包函数(如将函数做为另一个函数/方法的参数或者是返回结果为函数)中的this会因为闭包函数使用环境不同而变化。
<br />
prototype.js里加了一个bind方法可以把this重新绑回到原对象上(如fx方法所示),但如果返回的是闭包函数,则其中的this会指向新的object(如rf2方法所示指向了window)
</body>
</html>

Tuesday, January 08, 2008

Where the singleton methods live in Ruby [R4R 13.1.1]

Ruby, as usual, has a simple answer to this tricky question: An object's singleton methods live in the object's singleton class. Every object really has two classes:
■ The class of which it is an instance
■ Its singleton class

Friday, November 16, 2007

R4R and PR2 environment top-level method 学习笔记

R4R
Defining a top-level method
Suppose you define a method at the top level:


def talk
puts "Hello"
end

Who, or what, does the method belong to? It’s not inside a class or module definition block, so it doesn’t appear to be an instance method of a class or module. It’s not attached to any particular object (as in def obj.talk), so it’s not a singleton method. What is it?
By special decree (this is just the way it works!), top-level methods are private instance methods of the Kernel module.
That decree tells you a lot.
Because top-level methods are private, you can’t call them with an explicit receiver; you can only call them by using the implied receiver, self. That means self must be an object on whose method search path the given top-level method lies.

The default object (self) and scope
But every object’s search path includes the Kernel module, because the class Object mixes in Kernel, and every object’s class has Object as an ancestor. That means you can always call any top-level method, wherever you are in your program.
It also means you can never use an explicit receiver on a top-level method.
To illustrate this, let’s extend the talk example. Here it is again, with some code that exercises it:

def talk
puts "Hello"
end
puts "Trying 'talk' with no receiver..."
talk
puts "Trying 'talk' with an explicit receiver..."
obj = Object.new
obj.talk

The first call to talk succeeds; the second fails, because you’re trying to call a private method with an explicit receiver.
The rules concerning definition and use of top-level methods brings us all the way back to some of the bareword methods we’ve been using since as early as chapter1(R4R book). You’re now in a position to understand exactly how those methods work.

Programming Ruby 2nd
Top-Level Execution Environment
Many times in this book we’ve claimed that everything in Ruby is an object. However, we’ve used one thing time and time again that appears to contradict this—the top-level Ruby execution environment.
puts "Hello, World"
Not an object in sight. We may as well be writing some variant of Fortran or BASIC.
But dig deeper, and you’ll come across objects and classes lurking in even the simplest code.
We know that the literal "Hello, World" generates a Ruby String, so that’s one object. We also know that the bare method call to puts is effectively the same as self.puts. But what is self?
self.class ! Object
At the top level, we’re executing code in the context of some predefined object. When we definemethods, we’re actually creating (private) instancemethods for class Object.
This is fairly subtle; as they are in class Object, these methods are available everywhere.
And because we’re in the context of Object, we can use all of Object’s methods (including those mixed-in from Kernel) in function form. This explains why we
can call Kernel methods such as puts at the top level (and indeed throughout Ruby): these methods are part of every object. Top-level instance variables also belong to this top-level object.

命令行中定义的其实是定义在Kernel中的私有方法,并被Mix-in到Object类中成为其对象私有实例方法。因为class Module (< Object)和class Class (< Module)这3者的继承关系,所以控制台里定义的方法在module和class实例对象中可以调用。

Friday, August 24, 2007

Rails controller request and response methods and instance_variables


class TestController < ApplicationController
before_filter { |controller| p controller.request.methods.sort; p controller.request.instance_variables }
after_filter { |controller| p controller.response.methods.sort; p controller.response.instance_variables }

def index
end
end


# ["==", "===", "=~", "__id__", "__send__", "`", "accepts", "b64encode", "blank?", "cgi", "cgi=", "class", "clone", "content_type", "cookies", "copy_instance_variables_from", "daemonize", "dclone", "decode64", "decode_b", "delete?", "display", "domain", "dup", "enable_warnings", "encode64", "env", "eql?", "equal?", "extend", "extend_with_included_modules_from", "extended_by", "formatted_post?", "freeze", "frozen?", "gem", "get?", "hash", "head?", "host", "host_with_port", "id", "inspect", "instance_eval", "instance_exec", "instance_of?", "instance_values", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "kind_of?", "load", "method", "method_missing", "methods", "nil?", "object_id", "parameters", "path", "path_parameters", "path_parameters=", "port", "port_string", "post?", "post_format", "pretty_inspect", "pretty_print", "pretty_print_cycle", "pretty_print_inspect", "pretty_print_instance_variables", "private_methods", "protected_methods", "protocol", "public_methods", "put?", "query_parameters", "query_string", "raw_post", "relative_url_root", "relative_url_root=", "remote_ip", "remove_subclasses_of", "request_parameters", "request_uri", "require", "require_gem", "require_library_or_gem", "reset_session", "respond_to?", "returning", "send", "server_software", "session", "session=", "session_options", "session_options=", "silence_stderr", "silence_stream", "silence_warnings", "singleton_methods", "ssl?", "standard_port", "subclasses_of", "subdomains", "suppress", "symbolized_path_parameters", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_json", "to_param", "to_s", "to_yaml", "to_yaml_properties", "to_yaml_style", "type", "unloadable", "untaint", "with_options", "xhr?", "xml_http_request?", "xml_post?", "yaml_post?"]
# ["@session", "@request_method", "@query_parameters", "@parameters", "@content_type", "@request_parameters", "@session_options", "@session_options_with_string_keys", "@symbolized_path_parameters", "@env", "@cgi", "@path_parameters"]
# ["==", "===", "=~", "__id__", "__send__", "`", "assigns", "assigns=", "b64encode", "blank?", "body", "body=", "charset", "charset=", "class", "clone", "content_type", "content_type=", "cookies", "cookies=", "copy_instance_variables_from", "daemonize", "dclone", "decode64", "decode_b", "display", "dup", "enable_warnings", "encode64", "eql?", "equal?", "extend", "extend_with_included_modules_from", "extended_by", "freeze", "frozen?", "gem", "hash", "headers", "headers=", "id", "inspect", "instance_eval", "instance_exec", "instance_of?", "instance_values", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "kind_of?", "layout", "layout=", "load", "method", "methods", "nil?", "object_id", "out", "pretty_inspect", "pretty_print", "pretty_print_cycle", "pretty_print_inspect", "pretty_print_instance_variables", "private_methods", "protected_methods", "public_methods", "redirect", "redirected_to", "redirected_to=", "redirected_to_method_params", "redirected_to_method_params=", "remove_subclasses_of", "require", "require_gem", "require_library_or_gem", "respond_to?", "returning", "send", "session", "session=", "silence_stderr", "silence_stream", "silence_warnings", "singleton_methods", "subclasses_of", "suppress", "taguri", "taguri=", "taint", "tainted?", "template", "template=", "to_a", "to_json", "to_param", "to_s", "to_yaml", "to_yaml_properties", "to_yaml_style", "type", "unloadable", "untaint", "with_options"]
# ["@session", "@headers", "@assigns", "@body", "@redirected_to", "@cgi", "@template"]

Friday, July 20, 2007

call() and apply() of Function methods

These methods allow you to invoke a function as if it were a method of some other object.

<script type="text/javascript" language="JavaScript">

function doc(str){
document.writeln(str);
document.writeln("<br />");
}

var str = 'test';
doc.call(String, str);

// This is similar to the following lines of code:
String.m = doc;
String.m(str);
delete String.m;

</script>

Saturday, March 24, 2007

Member overloading

Overloading

Both method calls and member accesses can be overloaded via the __call, __get and __set methods. These methods will only be triggered when your object or inherited object doesn't contain the member or method you're trying to access. All overloading methods must not be defined as static. In PHP 5.0.x, all overloading methods must be defined as public.

Since PHP 5.1.0 it is also possible to overload the isset() and unset() functions via the __isset and __unset methods respectively.
Member overloading
void __set ( string name, mixed value )
mixed __get ( string name )
bool __isset ( string name )
void __unset ( string name )
Class members can be overloaded to run custom code defined in your class by defining these specially named methods. The $name parameter used is the name of the variable that should be set or retrieved. The __set() method's $value parameter specifies the value that the object should set the $name.


<?php
class Setter
{
public $n = 1;
private $array_x = array('x' => 1, 'y' => 2, 'z' => 3);

private function __get($var)
{
echo "Getting {$var}: <br />";
if(isset($this->array_x[$var]))
{
return $this->array_x[$var] . "<br/>";
}
else
{
echo "Nothing get {$var} in array_x. <br />";
}
}

private function __set($name, $value)
{
echo "Setting {$value} to {$name}. <br/>";
if(isset($this->array_x[$name]))
{
$this->array_x[$name] = $value;
}
else
{
echo "{$name} Nothing find in array_x.<br/>";
}
}

private function __isset($name)
{
echo "isset {$name} ? ";
if(isset($this->array_x[$name]))
{
echo "Yes.<br/>";
}
else
{
echo "No.<br/>";
}
}

private function __unset($name)
{
echo "unset {$name} <br/>";
unset($this->array_x[$name]);
}
}
$s = new Setter();
echo $s->x;
echo $s->y;
$s->y = 100;
echo $s->y;
isset($s->x);
isset($s->a);
// echo isset($s->n);
$s->z;
unset($s->z);
isset($s->z);
?>

Method overloading

mixed __call ( string name, array arguments )

Class methods can be overloaded to run custom code defined in your class by defining this specially named method. The $name parameter used is the name as the function name that was requested to be used. The arguments that were passed in the function will be defined as an array in the $arguments parameter. The value returned from the __call() method will be returned to the caller of the method.


<?php
class Caller
{
private $x = array(1, 3, 5, 7, 9);

private function __call($func, $args)
{
echo "call missing method: {$func}<br>";
echo "<pre>";
print_r($args);
echo "</pre>";
return $this->x;
}
}

$c = new Caller();
$rs = $c->test(1, 3, 'test', 'array', 'args');
var_dump($rs);
?>

Tuesday, February 27, 2007

Defining Methods

A method is a function associated with an object. You define a method the same way you define a standard function. Then you use the following syntax to associate the function with an existing object:

object.methodname = function_name

where object is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function.

You can then call the method in the context of the object as follows:

object.methodname(params);

You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects; for example,


function displayCar() {
var result = "A Beautiful " + this.year + " " + this.make
+ " " + this.model;
pretty_print(result);
}

where pretty_print is function to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs.

You can make this function a method of car by adding the statement

this.displayCar = displayCar;

to the object definition. So, the full definition of car would now look like

function car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
this.displayCar = displayCar;
}

Sunday, February 25, 2007

Properties and Methods of the XMLHTTP Object

The techniques we’ve covered so far use standard browser features for purposes other than that for which they were intended. As such, they lack many features you might want out of RPC-over-HTTP, such as the ability to check HTTP return codes and to specify username/password authentication information for requests. Modern browsers let you do JavaScript RPCs in a much cleaner, more elegant fashion with a flexible interface supporting the needed features missing from the previously discussed hacks.
Internet Explorer 5 and later support the XMLHTTP object and Mozilla-based browsers provide an XMLHTTPRequest object. These objects allow you to create arbitrary HTTP requests (including POSTs), send them to a server, and read the full response, including headers. Table 19-1 shows the properties and methods of the XMLHTTP object.
Table 19-1: Properties and Methods of the XMLHTTP Object
































Property or Method
Description
readyState
Integer indicating the state of the request, either : 0 (uninitialized), 1 (loading), 2 (response headers received), 3 (some response body received), or 4 (request complete).
Onreadystatechange
Function to call whenever the readyState changes.
status
HTTP status code returned by the server (e.g., “200”).
statusText
Full status HTTP status line returned by the server (e.g., “200 OK”).
responseText
Full response from the server as a string.
responseXML
A Document object representing the server's response parsed as an XML document.
abort()
Cancels an asynchronous HTTP request.
getAllResponseHeaders()
Returns a string containing all the HTTP headers the server sent in its response. Each header is a name/value pair separated by a colon, and header lines are separated by a carriage return/linefeed pair.
getResponseHeader(headerName)
Returns a string corresponding to the value of the headerName header returned by the server (e.g., request.getResponseHeader("Set-cookie")).
open(method, url [, asynchronous[, user, password]])
Initializes the request in preparation for sending to the server. The method parameter is the HTTP method to use, for example, GET or POST. The url is the URL the request will be sent to. The optional asynchronous parameter indicates whether send() returns immediately or after the request is complete (default is true, meaning it returns immediately). The optional user and password arguments are to be used if the URL requires HTTP authentication. If no parameters are specified by the URL requiring authentication, the user will be prompted to enter it.
setRequestHeader(name, value)
Adds the HTTP header given by the name (without the colon) and value parameters.
send(body)
Initiates the request to the server. The body parameter should contain the body of the request, i.e., a string containing fieldname=value&fieldname2=value2… for POSTs or the empty string ("") for GETs.


Note
Since the interfaces of these objects as well as their functionality are identical, we’ll arbitrarily refer to both as XMLHTTP objects.

Note
Internet Explorer supports two properties not listed in Table 19-1. The responseBody property holds the server’s response as a raw (undecoded) array of bytes and responseStream holds an object implementing the IStream interface through which you can access the response. Mozilla supports the onload property to which you can set a function that will be called when an asynchronous request completes. However, as these properties are all browser-specific, we don’t discuss them. You can find more information about them on the respective browser vendors’ Web sites.
Some of the properties and methods listed in Table 19-1, such as responseText and getAllResponseHeaders(), won’t be available until the request has completed. Attempting to access them before they’re ready results in an exception being thrown.

Creating and Sending Requests
XMLHTTP requests can be either synchronous or asynchronous, as specified by the optional third parameter to open(). The send() method of a synchronous request will return only once the request is complete, that is, the request completes “while you wait.” The send() method of an asynchronous request returns immediately, and the download happens in the background. In order to see if an asynchronous request has completed, you need to check its readyState. The advantage of an asynchronous request is that your script can go on to other things while it is made and the response received, for example, you could download a bunch of requests in parallel.
To create an XMLHTTP object in Mozilla-based browsers, you use the XMLHttpRequest constructor:
var xmlhttp = new XMLHttpRequest();
In IE, you instantiate a new MSXML XHMLHTTP ActiveX object:
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
Once you have an XMLHTTP object, the basic usage for synchronous requests is
Parameterize the request with open().
Set any custom headers you wish to send with setRequestHeader().
Send the request with send().
Read the response from one of the response-related properties.
The following example illustrates the concept:
if (document.all)
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
else
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://www.example.com/somefile.html", false);
xmlhttp.send("");
alert("Response code was: " + xmlhttp.status)
The sequence of steps for an asynchronous request is similar:
Parameterize the request with open().
Set any custom headers you wish to send with setRequestHeader().
Set the onreadystatechange property to a function to be called when the request is complete.
Send the request with send().
The following example illustrates an asynchronous request:
if (document.all)
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
else
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", window.location);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4)
alert("The text of this page is: " + xmlhttp.responseText);
};
xmlhttp.setRequestHeader("Cookie", "FakeValue=yes");
xmlhttp.send("");
When working with asynchronous requests, you don’t have to use the onreadystatechange handler. Instead, you could periodically check the request’s readyState for completion.

POSTs
You can POST form data to a server in much the same way as issuing a GET. The only differences are using the POST method and setting the content type of the request appropriately (i.e., to “application/x-www-form-urlencoded”).
var formData = "username=billybob&password=angelina5";
var xmlhttp = null;
if (document.all)
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
else if (XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
if (xmlhttp)
{
xmlhttp.open("POST", "http://demos.javascriptref.com/xmlecho.php", false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(formData);
document.write("<hr>" + xmlhttp.responseText + "<hr>");
}