Home > Web Front-end > JS Tutorial > body text

The sixth way to write classes in javascript_js object-oriented

WBOY
Release: 2016-05-16 18:50:44
Original
798 people have browsed it

6. How to write classes in Prototype.js

Copy the code The code is as follows:

//prototype Code in .js
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
//Simplified
function Clazz() {
return function(){
this.initialize.apply(this,arguments);
}
}

Write a class as follows,
Copy the code The code is as follows:

//Class name Person
var Person = Class.create();

//Define Person through prototype rewriting
Person.prototype = {
initialize : function (name) {
this.name = name;
},
getName : function() {
return this.name;
},
setName : function(name) {
this.name = name;
}
}

//Create object
var p = new Person("jack");
console.log(p. constructor == Person);//false

initialize completes the initialization of the object (equivalent to the constructor), just write the methods in sequence.



There is a problem. You can see from the sentence p.constructor == Person is false. This is a small flaw in Prototype.js. The reason is that the prototype of Person has been rewritten. In order for the constructor to point to the correct constructor, you only need to maintain the constructor property when rewriting the prototype.
Copy code The code is as follows:

Person.prototype = {
constructor : Person, //Note here
initialize : function(name) {
this.name = name;
},
getName : function() {
return this.name;
},
setName : function(name) {
this.name = name;
}
}

Okay, now p.constructor == Person is true .
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!