6. Writing method
// Code in
var Class = {
create: function() {
return function() {
(this, arguments);
}
}
}
//Simplified
function Clazz() {
return function(){
(this,arguments);
}
}
Write a class as follows,
//Class name Person
var Person = ();
//Define Person through prototype rewrite
= {
initialize : function(name) {
= name;
},
getName : function() {
return ;
},
setName : function(name) {
= name;
}
}
//Create an object
var p = new Person("jack");
( == Person);//false
initialize completes the initialization of the object (equivalent to the constructor), and write the method down in sequence.
There is a problem. You can see through this sentence == Person is false, which is a small flaw. The reason is that Person's prototype was rewritten. In order for the constructor to point to the correct constructor, just maintain the constructor attributes during prototype rewriting.
= {
constructor: Person,//Note here
initialize : function(name) {
= name;
},
getName : function() {
return ;
},
setName : function(name) {
= name;
}
}
OK, then == Person is true.
Copy the codeThe code is as follows:
// Code in
var Class = {
create: function() {
return function() {
(this, arguments);
}
}
}
//Simplified
function Clazz() {
return function(){
(this,arguments);
}
}
Write a class as follows,
Copy the codeThe code is as follows:
//Class name Person
var Person = ();
//Define Person through prototype rewrite
= {
initialize : function(name) {
= name;
},
getName : function() {
return ;
},
setName : function(name) {
= name;
}
}
//Create an object
var p = new Person("jack");
( == Person);//false
initialize completes the initialization of the object (equivalent to the constructor), and write the method down in sequence.
There is a problem. You can see through this sentence == Person is false, which is a small flaw. The reason is that Person's prototype was rewritten. In order for the constructor to point to the correct constructor, just maintain the constructor attributes during prototype rewriting.
Copy the codeThe code is as follows:
= {
constructor: Person,//Note here
initialize : function(name) {
= name;
},
getName : function() {
return ;
},
setName : function(name) {
= name;
}
}
OK, then == Person is true.