6. How to write classes in Prototype.js
//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,
//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.
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 .
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