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

How to implement private attributes in JavaScript (2)_javascript skills

WBOY
Release: 2016-05-16 17:11:05
Original
1034 people have browsed it

In the previous article, I wrote a tool function $class, and this article will improve it as follows. Implement the following functions

1, inheritance

2. When a subclass inherits a parent class, it does not inherit the private attributes of the parent class

Copy the code The code is as follows:

/**
 * @param {String} className
 * @param {String/Function} superCls
 * @param {Function} classImp
 */
function $class(className, superCls, classImp){
if(superCls === '') superCls = Object;
function clazz (){
                                                                                   = new superCls();
var _super = superCls.prototype;
window[className] = clazz;
classImp.apply(p, [_super]);
}


Write a parent class first



Copy the code
The code is as follows:/** * Parent class Person
*/
$class('Person','',function(){
// Private property age
var age;
this.init = function(n, a){
                                                                                                                  return this.name;
};
this.setName = function(name){
this.name = name;
}
this.getAge = function(){
return age;
};
this.setAge = function(a){
age = a;
};
});


Write a subclass, Inherited from Person




Copy code


The code is as follows:


$class("Man",Person, function(supr){
var school; this.init = function(n, a, s){ supr.init.apply(this, [n,a]); school = s; } this.getSchool = function(){ return school;
};
this.setSchool = function(s){
school = s;
};
});


new a subclass instance




Copy code


The code is as follows :


var m = new Man('tom', 25, 'pku');
console.log(m.name); // tom can inherit the common attribute name of the parent class Directly use the dot operator to obtain console.log(m.age); // undefined The private attribute age of the parent class cannot be directly used to obtain console.log(m.getAge()); // 25 The private attribute age can be obtained through the parent class’s public method getAge console.log(m.school); // undefined Man’s own private attribute still cannot be obtained through the dot operator console.log(m.getSchool) ()); // pku obtains the private attribute school
through the getSchool() method
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