当前位置:网站首页>JS__ Inheritance mode, namespace, object enumeration__ Duyi
JS__ Inheritance mode, namespace, object enumeration__ Duyi
2022-06-25 20:57:00 【Leap soil and tea】
Inherit the history of development
- Traditional forms ——> Prototype chain
Too much inheritance of useless attributes
Grand.prototype.lastName = "Ji";
function Grand() {
}
var grand = new Grand();
Father.prototype = grand;
function Father() {
this.name = 'hehe';
}
var father = new Father();
Son.prototype = father;
function Son() {
}
var son = new Son();
- Borrow constructor
Cannot inherit the prototype of the borrowed constructor
Every constructor takes one more function
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student (name, age, sex, grade) {
Person.call(this, name, age, sex);
this.grade = grade;
}
var student = new Student();
- Sharing prototypes
You can't change your own prototype
Father.prototype.lastName = "Deng";
function Father() {
}
function Son() {
}
Son.prototype = Father.prototype
var son = new Son();
var father = new Father();
// Father.prototype
//Father Son
Abstract function , Packaging function , Implementation inheritance
function inherit(Target, Origin) {
Target.prototype = Origin.prototype;
}
inherit(Son,Father);
var son = new Son();
When you change your prototype , Also changed other prototypes
Father.prototype.lastName = "Deng";
function Father() {
}
function Son() {
}
function inherit(Target, Origin) {
Target.prototype = Origin.prototype;
}
inherit(Son, Father);
Son.prototype.sex = "male";
var son = new Son();
var father = new Father();
//Son.prototype and Father.prototype Is the same point >father.sex <male
- The holy grail mode
Add personalization attributes , Does not affect other prototypes ; Inherit your own prototype , Also inherit the public prototype
function inherit(Target, Origin) {
// Inheritance is encapsulated into functions
function F() {
}
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;// Give Way son.constructor Point to itself
Target.prototype.uber = Origin.prototype;// It means that it really inherits from Father
}
Father.prototype.lastName = "Deng";
function Father() {
}
function Son() {
}
inherit(Son, Father);
var son = new Son();
var father = new Father();
//Son.prototype.sex = "male";
//>son.sex <male
//>father.sex <undefined
//son.__proto__ —-> new F().__proto__ —-> Father.prototype
// recommend
var inherit = (function () {
var F = function () {
};// Privatization variables , Put closure
return function (Target, Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
}());
Section of closure 3 Point application : Can achieve encapsulation , Privatization variables
function Deng(name, wife) {
var prepareWife = "xiaozhang";// Privatization variables
this.name = name;
this.wife = wife;
this.divorce = function () {
// Method
this.wife = prepareWife;
}
this.changePerpareWife = function(target) {
// Method
prepareWife = target;
}
this.sayPreparewife = function () {
// Method
console.log(prepareWife);
}
}
var deng = new Deng('deng', 'xiaoliu');
deng.divorce();
// To form a closure ,divorce,changePerpareWife,sayPerparewife Three functions are saved externally , Stored functions Deng Execution context AO, So the three functions can be accessed externally at will
//>deng.prepareWife <undefined Private variables cannot be accessed externally , It's not an attribute of an object , Belonging to the closure
//>deng.sayPreparewife <xiaozhang Methods that implement object settings can access privatized variables
Namespace
Original method : Manage variables , To prevent pollution , For modular development
var org = {
department1 : {
jicheng : {
name : "abc",
age : 123,
},
xuming : {
}
},
department2 : {
zhangsan : {
},
lisi : {
}
}
}
var jicheng = org.department1.jicheng;
jicheng.name
Modern solutions : Section of closure 4 Point application —— Modular development
Privatize your own variables with closures (name), Avoid duplicate naming ;
var name = 'bcd';
var init = (function () {
var name = 'abc';
function callName() {
console.log(name);
}
return function () {
callName();
}
}())
var initDeng = (function () {
var name = 123;
function callName() {
console.log(name);
}
return function () {
callName();// Function reuse , Extract to closure
}
}())
init();//abc
initDeng();//123
Chain call to method ( imitation jQuery)
var deng = {
smoke : function () {
console.log('Smoking,... xuan cool!!!');
//return undefined
return this;
},
drink : function () {
console.log('drinkin..., ye cool!');
return this;
},
perm : function () {
console.log('perming..., cool!');
return this;
}
}
deng.smoke().drink().perm().smoke().drink();// Can be executed
Attribute representation
obj.prop( attribute )
obj[“prop”] ( Attribute name in string form ) Run fast , No conversion
obj.name --> obj[‘name’], There must be a string in brackets , direct writing name It becomes a variable .
var obj = {
wife1 : {
name : "xiaoliu"},
wife2 : {
name : "xiaozhang"},
wife3 : {
name : "xiaomeng"},
wife4 : {
name : "xiaowang"},
sayWife : function (num){
// Method
return this['wife' + num];// To realize the splicing of attribute names, you can only use obj["prop"]
}
}
Enumeration of objects
var arr = [1,3,3,4,5,6,7,8,9];
// Traversal array enumeration enumeration
for(var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Traversal properties for in Traversing objects ( Including attributes on the prototype chain , Any manually added attributes , But not the topmost Object.prototype The default attribute of )
1.hasOwnProperty Returns a Boolean value , The way to judge whether it really belongs to you
var obj = {
name : '13',
age : 123,
sex : "male",
height : 180,
weight : 75
__proto__ : {
lastname : 'deng',// Properties on prototypes
__proto__ : Object.prototype
}
}
Object.prototype.abc = '123';//ok Include manually added attributes
for(var prop in obj) {
//prop Represents the property name ( alternative ) obj Is constant
if(!obj.hasOwnProperty(prop)){
//console.lgo(prop + " " + typeof(prop));//string type
//console.log(obj.prop);// In essence obj['prop'], It's equivalent to visiting prop attribute , Print 5 individual undefined
console.log(obj[prop]);// You must write square brackets in the enumeration !!!
}
}
// A method that does not belong to you :deng 123
2.in( You can only judge whether an object can call this property , Cannot determine whether the attribute belongs to this object ) Use less
‘height’ in obj —> true
‘lastname’ in obj —> true
3.instanceof
function Person() {
}
var person = new Person();
//A object Is it right? B Constructed by constructors
// see A Object's prototype chain Is there any B The prototype of the
//A instanceof B
person instanceof Person ---> true
person instanceof Object ---> true
[] instanceof Array -->true
[] instanceof Object -->true
person instanceof Array --> false
{
} instanceof Person --> false
Determine whether the variable is an array or object ?
Law 1 :constructor
[].constructor;//Array
var obj = {
};
obj.constructor;//Object
Law two :instanceof
[] instanceof Array;//true, Only use Array distinguish
var obj = {
};
obj instanceof Array;//false
Law three :toString() Method
Object.prototype.toString.call([]);//"[object Array]" this yes Array
Object.prototype.toString.call(123);//"[object Number]" this yes Numbers
Object.prototype.toString.call({
});//"[object Object]" this yes object
Object.prototype.toString = function() {
// distinguish this
// Return the corresponding result
}
var obj = {
};
obj.toString();//"[object Object]"
//obj call toString --> this yes obj
边栏推荐
- R language quantile autoregressive QAR analysis pain index: time series of unemployment rate and inflation rate
- [distributed system design profile (1)] raft
- SaaS privatization deployment scheme
- Insert and update each database
- 1.0-mq getting started and using
- Interview shock: talk about thread life cycle and transformation process?
- Flexible scale out: from file system to distributed file system
- 同花顺炒股软件开户是合法的吗?安全吗
- Idea implements hot deployment
- 2022 oceanbase technical essay contest officially opened | come and release your force
猜你喜欢
Global netizens Yuanxiao created a picture of appreciating the moon together to experience the creativity of Baidu Wenxin big model aigc
[distributed system design profile (1)] raft
Chrome plugin installation
Uncover n core 'black magic' of Presto + alluxio

Cvpr2020 | the latest cvpr2020 papers are the first to see, with all download links attached!
This is a simple and cool way to make large screen chart linkage. Smartbi will teach you
New generation engineers teach you how to play with alluxio + ml (Part 2)
Cloud development practice of the small program for brushing questions in the postgraduate entrance examination - page design and production (home page of the question bank, ranking page, my)

Xshell mouse configuration

A simple file searcher
随机推荐
Patrol script
Yolov4 improved version comes out! Yolov4 extended edition! Yolov4 launched scaled-yolov4: scaling cross stage partial network
Live broadcast preview | front line experts invite you to talk: the value of data science enabling multiple application scenarios
After 20 days' interview, I finally joined Ali (share the interview process)
Several ways to obtain domain administrator privileges
How does zhiting home cloud and home assistant access homekit respectively? What is the difference between them?
Is it legal to open an account for flush stock trading software? Is it safe?
Ensure the decentralization and availability of Oracle network
An unusual interview question: why doesn't the database connection pool adopt IO multiplexing?
Literals and type conversions of basic data types
Nmap is simple and practical
Log4j2 vulnerability battle case
1.0-mq getting started and using
Is it safe for qiniu school to open an account in 2022?
Install JDK, MySQL and nexus under Linux (tar package installation)
Interviewer: why does TCP shake hands three times and break up four times? Most people can't answer!
Vbpr (visual Bayesian personalized ranking) paper summary
OLED driver learning based on ssd1306 (I): SSD Chinese command table (handling)
Yunzhisheng atlas supercomputing platform: computing acceleration practice based on fluid + alluxio (Part I)
Chrome plugin installation