Home  >  Article  >  Web Front-end  >  Two different ways to create classes and objects in JS_Basic knowledge

Two different ways to create classes and objects in JS_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:40:011049browse

In JavaScript, when you define a new function, you actually declare a new class, and the function itself is equivalent to the constructor of the class. The following code shows you two different ways to create a new Person class, and the definition of Person.prototype follows the function definition.

var Person = function(name) { // 一个匿名函数, 并将这个函数赋值给一个Person变量, 此时Person成为一个类 

this.name = name; 

} 

function Person(name) { // 直接定义一个叫做Person的函数表示Person类 

this.name = name; 

} 

Person.prototype = { // 定义Person的prototype域 

printName: function() { // 定义一个print函数 

alert(this.name); 

} 

}

After you declare a class through a function, you can instantiate the class through the new operator. In this way, you can call the member functions of the class to complete your logic.

var person = new Person("Joe Smith"); // 使用new操作符来新建一个Person的实例, 并赋给变量person 
person.printName(); // person就可以看作是一个实例的引用(reference), 所以可以通过这个引用来调用Person类中的成员函数

Let’s summarize the entire process and steps of creating an instance of a new class:

1. Declare a new class by defining a function (anonymous or with a real name).
2. If necessary, define the prototype field of this new class.
3. Use the new operator followed by the function you define to create a new class instance. Once the JavaScript compiler encounters the new operator, it actually creates an empty class instance variable.
4. Copy all the attributes and methods in the prototype field of this class to this new instance, and point all this pointers in its member functions to this newly created instance.
5. Next, execute the function immediately following the new operator.
6. When you execute this function, if you try to assign a value to a property that does not exist, the JavaScript compiler will automatically create the property for you within the scope of this instance.
7. After the function is executed, return the initialized instance.

In Prototype, using the Class object, you can declare a new object in a relatively simple way. By using Class.create(), prototype creates a default constructor function initialize() for you. Once you implement this function, you can create a new instance of the class in a way similar to the constructor function in Java.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn