class Example{public int data = 0; // Each instance of Example holds its internal data. This is a "field", or "member variable".
public void UpdateData() // .. and manipulates it (This is a method by the way){data = data + 1;}
public void PrintData() // This is also a method{Console.WriteLine(data);}}
class Program{public static void Main(){Example exampleObject1 = new Example();Example exampleObject2 = new Example();
exampleObject1.UpdateData();exampleObject1.UpdateData();
exampleObject2.UpdateData();
exampleObject1.PrintData(); // Prints "2"exampleObject2.PrintData(); // Prints "1"}}
public static int addValues( int x, int y ) {return x + y;}
眼熟?那是因为JavaC++C++C
最后只是一个概念,在实现中它们可能看起来相同,但在OO留档中这些被称为方法。
下面是Java中以前的雇员对象的示例。
public class Employee {
Department department;String name;
public String whatsYourName(){return this.name;}public String whatsYourDeparmentsName(){return this.department.name();}public String whatAreYouDoing(){return "nothing";}// Ignore the following, only set here for completnesspublic Employee( String name ) {this.name = name;}
}
// Usage sample.Employee employee = new Employee( "John" ); // Creates an employee called John
// If I want to display what is this employee doing I could use its methods.// to know it.String name = employee.whatIsYourName():String doingWhat = employee.whatAreYouDoint();
// Print the info to the console.
System.out.printf("Employee %s is doing: %s", name, doingWhat );
Output:Employee John is doing nothing.
# perfectly normal functiondef hello(greetee):print "Hello", greetee
# generalise a bit (still a function though)def greet(greeting, greetee):print greeting, greetee
# hide the greeting behind a layer of abstraction (still a function!)def greet_with_greeter(greeter, greetee):print greeter.greeting, greetee
# very simple class we can pass to greet_with_greeterclass Greeter(object):def __init__(self, greeting):self.greeting = greeting
# while we're at it, here's a method that uses self.greeting...def greet(self, greetee):print self.greeting, greetee
# save an object of class Greeter for laterhello_greeter = Greeter("Hello")
# now all of the following print the same messagehello("World")greet("Hello", "World")greet_with_greeter(hello_greeter, "World")hello_greeter.greet("World")
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {return a * b; // Function returns the product of a and b}
var test = something.test();这里test()可以是某个对象的方法或自定义定义的内置对象原型,这里有更多解释:
JavaScript方法是可以在对象上执行的操作。
JavaScript方法是包含函数定义的属性。
JavaScript中字符串的内置属性/方法:
var message = "Hello world!";var x = message.toUpperCase();//Output: HELLO WORLD!
自定义示例:
function person(firstName, lastName, age, eyeColor) {this.firstName = firstName;this.lastName = lastName;this.age = age;this.eyeColor = eyeColor;this.changeName = function (name) {this.lastName = name;};}
something.changeName("SomeName"); //This will change 'something' objject's name to 'SomeName'
您也可以为String、Array等定义属性,例如
String.prototype.distance = function (char) {var index = this.indexOf(char);
if (index === -1) {console.log(char + " does not appear in " + this);} else {console.log(char + " is " + (this.length - index) + " characters from the end of the string!");}};
var something = "ThisIsSomeString"
// now use distance like this, run and check console log
something.distance("m");
class User {public string name; // I made it public intentionally
// Each instance method takes a hidden reference to "this"public void printName(/*User & this*/) {cout << this.name << endl;}};
相当于
public getName(User & user) {// No syntactic sugar, passing a reference explicitlycout << user.name << endl;}
在Java世界里你总是听到“只有OOP类/对象,没有函数”,但是如果你详细观察Java中的static methods,它们实际上是在全局/空上下文(或类的上下文,没有实例化)中,所以只是函数没有对象。Java老师可以告诉你,那functions were rudiment of C in C++ and dropped in Java,但他们告诉你是为了简化历史和避免新手不必要的问题。如果你看到Java7版本后,你可以找到许多纯函数编程的元素(即使不是来自C,但从1988年开始 Lisp)用于简化并行计算,它不是OOP类风格。