In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "detailed explanation of JavaScript object-oriented programming". In daily operation, I believe many people have doubts about the detailed explanation of JavaScript object-oriented programming. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "detailed explanation of JavaScript object-oriented programming". Next, please follow the editor to study!
Preliminary study
We know that the definitions of variables in Javascript are basically as follows:
Var name = 'Chen Hao';; var email =' haoel (@) hotmail.com'; var website = 'http://coolshell.cn';
If you want to write with an object, it looks like this:
Var chenhao = {name: 'Chen Hao', email:' haoel (@) hotmail.com', website: 'http://coolshell.cn'}
So, I can visit like this:
/ / chenhao.name; chenhao.email; chenhao.website; as a member / / chenhao as a hash map ["name"]; chenhao ["email"]; chenhao ["website"]
With regard to functions, we know that Javascript's functions look like this:
Var doSomething = function () {alert ('Hello World.');}
So, we can do this:
Var sayHello = function () {var hello = "Hello, Ichimm" + this.name + ", my email is:" + this.email + ", my website is:" + this.website; alert (hello);}; / / Direct assignment, which is very similar to the function pointer chenhao.Hello = sayHello; chenhao.Hello () of CumberCure +.
I believe that these things are relatively simple, we all understand. You can see that the javascript object function is declared directly, assigned directly, and used directly. The dynamic language of runtime.
There is also a more standard way of writing:
/ / as we can see, it uses function to do class. Var Person = function (name, email, website) {this.name = name; this.email = email; this.website = website; this.sayHello = function () {var hello = "Hello, Isimm" + this.name + ",\ n" + "my email is:" + this.email + ",\ n" + "my website is:" + this.website Alert (hello);};}; var chenhao = new Person ("Chen Hao", "haoel@hotmail.com", "http://coolshell.cn"); chenhao.sayHello ())
By the way, to delete the properties of an object, it is simple:
Delete chenhao ['email']
From the above examples, we can see the following points:
The data and membership encapsulation of ◆ Javascript is simple. No class is entirely an object operation. Pure dynamic!
The this pointer in ◆ Javascript function is critical, and if not, it is a local variable or local function.
The ◆ Javascript object member function can be temporarily declared when it is used, and a global function can be directly assigned to it.
The member functions of ◆ Javascript can be modified on the instance, that is, the behavior of different instances with the same function name is not necessarily the same.
Property configuration-Object.defineProperty
Take a look at the following code first:
/ / create an object var chenhao = Object.create (null); / / set a property Object.defineProperty (chenhao, 'name', {value:' Chen Hao', writable: true, configurable: true, enumerable: true}) / / set multiple properties Object.defineProperties (chenhao, {'email': {value:' haoel@hotmail.com', writable: true, configurable: true, enumerable: true}, 'website': {value:' http://coolshell.cn',) Writable: true, configurable: true, enumerable: true}})
Let's talk about what these attribute configurations mean.
Writable: whether the value of this property can be changed.
Configurable: whether the configuration of this property can be changed.
Enumerable: whether this property can be found in for … Iterate through the in loop or enumerate it in Object.keys.
Value: property value.
Get () / set (_ value): get and set accessors.
Get/Set accessor
With regard to the get/set accessor, it means to replace value with get/set (which cannot be used with value), as shown in the following example:
Var age = 0; Object.defineProperty (chenhao, 'age', {get: function () {return age+1;}, set: function (value) {age = value;} enumerable: true, configurable: true}); chenhao.age = 100 / / call set alert (chenhao.age); / / call get output 101 (+ 1 in get)
Let's look at a more practical example-- using existing attributes (age) to construct new attributes (birth_year) through get and set:
Object.defineProperty (chenhao, 'birth_year', {get: function () {var d = new Date (); var y = d.getFullYear (); return (y-this.age)) }, set: function (year) {var d = new Date (); var y = d.getFullYear (); this.age = y-year;}}); alert (chenhao.birth_year); chenhao.birth_year = 2000 Alert (chenhao.age)
It seems a little troublesome to do so, you say, why don't I write it like this:
Var chenhao = {name: "Chen Hao", email: "haoel@hotmail.com", website: "http://coolshell.cn", age: 100, get birth_year () {var d = new Date (); var y = d.getFullYear (); return (y-this.age) }, set birth_year (year) {var d = new Date (); var y = d.getFullYear (); this.age = y-year;}}; alert (chenhao.birth_year); chenhao.birth_year = 2000; alert (chenhao.age)
Yes, you can, but with defineProperty () you can do these things:
1) set the property configuration such as writable,configurable,enumerable.
2) add attributes to an object dynamically. For example: some DOM targets of HTML.
View object property configuration
If you view and manage these configurations of an object, here is a program that can output the properties and configuration of the object, and so on:
/ / lists the properties of the object. Function listProperties (obj) {var newLine = ""; var names = Object.getOwnPropertyNames (obj); for (var I = 0; I
< names.length; i++) { var prop = names[i]; [xss_clean](prop + newLine); // 列出对象的属性配置(descriptor)动用getOwnPropertyDescriptor函数。 var descriptor = Object.getOwnPropertyDescriptor(obj, prop); for (var attr in descriptor) { [xss_clean]("..." + attr + ': ' + descriptor[attr]); [xss_clean](newLine); } [xss_clean](newLine); } } listProperties(chenhao); call,apply, bind 和 this 关于Javascript的this指针,和C++/Java很类似。 我们来看个示例:(这个示例很简单了,我就不多说了) function print(text){ [xss_clean](this.value + ' - ' + text+ ' '); } var a = {value: 10, print : print}; var b = {value: 20, print : print}; print('hello');// this =>Global, output "undefined-hello" a.print ('a'); / / this = > a, output "10-a" b.print ('b'); / / this = > b, output "20-b" a ['print'] (' a'); / / this = > a, output "10-a"
Let's take a look at call and apply. The difference between these two functions is that the parameters look different, and the other is that the performance is different, and the performance of apply is much worse. (for performance, go to JSPerf for a run.)
Print.call (a,'a'); / / this = > a, output "10-a" print.call (b,'b'); / / this = > b, output "20-b" print.apply (a, ['a']); / / this = > a, output "10-a" print.apply (b, ['b']); / / this = > b, output "20-b"
But after bind, the this pointer may be different, but because Javascript is dynamic. Such as the following example
Var p = print.bind (a); p ('a'); / / this = > a, output "10-a" p.call (b,'b'); / / this = > a, output "10-b" p.apply (b, ['b']); / / this = > a, output "10-b"
Inheritance and overloading
With the examples above, we can actually inherit through Object.create (), as shown in the following code, Student inherits from Object.
Var Person = Object.create (null); Object.defineProperties (Person, {'name': {value:' Chen Hao'}, 'email': {value:' haoel@hotmail.com'}, 'website': {value:' http://coolshell.cn'}}); Person.sayHello = function () {var hello = "
Hello, I am "+ this.name +"
+ "my email is:" + this.email + "
+ "my website is:" + this.website; [xss_clean] (hello + "
");} var Student = Object.create (Person); Student.no =" 1234567 "; / / Student ID Student.dept =" Computer Science "; / / Department / / use the attribute of Person [xss_clean] (Student.name +'+ Student.email +''+ Student.website +')
'); / / use the Person method Student.sayHello (); / / overload the SayHello method Student.sayHello = function (person) {var hello = "
Hello, I am "+ this.name +"
+ "my email is:" + this.email + "
+ "my website is:" + this.website + "
+ "my student no is:" + this. No + "
"+" my departent is: "+ this. Dept; [xss_clean] (hello +'
');} / / call Student.sayHello () again; / / check the properties of Student (only no, dept and overloaded sayHello) [xss_clean] ('
'+ Object.keys (Student) +'
')
In the above example, we can see that the properties in Person are not really copied into Student, but we can access them. This is because Javascript implements this mechanism with delegates. In fact, this is Prototype,Person is the Prototype of Student.
When our code needs an attribute, Javascript's engine will first look to see if there is this property in the current object, and if not, it will find out whether his Prototype object has this property and continue until it is found or until there is no Prototype object.
To prove this, we can use Object.getPrototypeOf () to test it:
Student.name = 'aaa'; / / output aaa [xss_clean] ('
'+ Student.name +'
'); / / output Chen Hao [xss_clean] ('
'+ Object.getPrototypeOf (Student). Name +'
')
Therefore, you can also call the function of the parent object in the function of the child object, just like Base::func () in C++. Therefore, our method of overloading hello can use the code of the parent class, as shown below:
/ / the new overloaded SayHello method Student.sayHello = function (person) {Object.getPrototypeOf (this) .sayHello.call (this); var hello = "my student no is:" + this. No + "
"+" my departent is: "+ this. Dept; [xss_clean] (hello +'
');}
This is powerful.
Combination
The above thing does not meet our requirements, and we may want these objects to be really combined. Why do you want to combine? Because we all know that this is the most important thing that OO designed. However, this is not a particularly good support for Javascript, but we can still take care of one thing.
First, we need to define a function of Composition: (target is the action object, source is the source object). The following code is very simple, which is to take out the properties in source one by one and define them into target.
Function Composition (target, source) {var desc = Object.getOwnPropertyDescriptor; var prop = Object.getOwnPropertyNames; var def_prop = Object.defineProperty; prop (source). ForEach (function (key) {def_prop (target, key, desc (source, key)}) return target;}
With this function, we can play here:
/ artist var Artist = Object.create (null); Artist.sing = function () {return this.name + 'starts singing...';} Artist.paint = function () {return this.name +' starts painting...';} / / athlete var Sporter = Object.create (null); Sporter.run = function () {return this.name + 'starts running...' } Sporter.swim = function () {return this.name + 'starts swimming...';} Composition (Person, Artist); [xss_clean] (Person.sing () +'
'); [xss_clean] (Person.paint () +'
'); Composition (Person, Sporter); [xss_clean] (Person.run () +'
'); [xss_clean] (Person.swim () +'
); / / see what's in Person? (output: sayHello,sing,paint,swim,run) [xss_clean] ('
'+ Object.keys (Person) +'
')
Prototype and inheritance
Let's talk about Prototype first. Let's take a look at the following routine, which doesn't need to be explained. It's a lot like function pointers in C, which we see a lot in C.
Var plus = function (x _ ray) {[xss_clean] (x +'+ y +'='+ (x _ ray) +'
'); return x + y;}; var minus = function (XMague y) {[xss_clean] (x +' -'+ y +'='+ (xmery) +'
); return x-y;}; var operations = {'+': plus,'-': minus}; var calculate = function (x, y, operation) {return operations [operation] (x, y);}; calculate (12, 4,'+'); calculate (24, 3,'-')
So, can we encapsulate these things? we need to use prototype. Look at the following example:
Var Cal = function (x, y) {this.x = x; this.y = y;} Cal.prototype.operations = {'+': function (x, y) {return xray;},'-': function (x, y) {return x operation;}}; Cal.prototype.calculate = function (operation) {return this.operations [operation] (this.x, this.y);}; var c = new Cal (4,5) C.calculate ('+'); c.calculate ('-')
This is the use of prototype, and prototype is the most important content in the language javascript. There are too many articles about the beginning of this thing on the Internet. To put it bluntly, prototype is an extension of an object, which is characterized by "copying" an existing instance to return a new instance, rather than creating a new instance. The replicated instance is what we call a "prototype", which is customizable (of course, there is no real copy, it's just a delegate). In the above example, we extend the instance Cal to have a property of operations and a method of calculate.
In this way, we can implement inheritance through this feature. Remember our first Person, the following example is to create a Student to inherit Person.
Function Person (name, email, website) {this.name = name; this.email = email; this.website = website;}; Person.prototype.sayHello = function () {var hello = "Hello, I am" + this.name + "
+ "my email is:" + this.email + "
"+" my website is: "+ this.website; return hello;}; function Student (name, email, website, no, dept) {var proto = Object.getPrototypeOf; proto (Student.prototype) .constructor.call (this, name, email, website); this.no = no; this.dept = dept;} / / inheritance prototype Student.prototype = Object.create (Person.prototype) / / reset constructor Student.prototype.constructor = Student; / / overload sayHello () Student.prototype.sayHello = function () {var proto = Object.getPrototypeOf; var hello = proto (Student.prototype) .sayHello.call (this) +'
'; hello + = "my student no is:" + this. No + "
"+" my departent is: "+ this. Dept; return hello;}; var me = new Student (" Chen Hao "," haoel@hotmail.com "," http://coolshell.cn", "12345678", "Computer Science"); [xss_clean] (me.sayHello ())
Compatibility
The above code doesn't necessarily work in all browsers, because it follows the ECMAScript 5 specification. For the browser compatibility list of ECMAScript 5, you can see the ES5 browser compatibility Table here.
All the code in this article has been tested in the Chrome*** version.
Here are some functions that can be used in browsers that are not compatible with ES5:
Object.create () function
Function clone (proto) {function Dummy () {} Dummy.prototype = proto; Dummy.prototype.constructor = Dummy; return new Dummy (); / / equivalent to Object.create (Person);} var me = clone (Person)
DefineProperty () function
Function defineProperty (target, key, descriptor) {if (descriptor.value) {target [key] = descriptor.value;} else {descriptor.get & & target.__defineGetter__ (key, descriptor.get); descriptor.set & & target.__defineSetter__ (key, descriptor.set);} return target}
Keys () function
Function keys (object) {var result, key result = []; for (key in object) {if (object.hasOwnProperty (key)) result.push (key)} return result;}
Object.getPrototypeOf () function
Function proto (object) {return! object? Null:'_ _ proto__' in object? Object.__proto__: / * not exposed? * / object.constructor.prototype}
Bind function
Var slice = [] .slice function bind (fn, bound_this) {var bound_args bound_args = slice.call (arguments, 2) return function () {var args args = bound_args.concat (slice.call (arguments)) return fn.apply (bound_this, args)}} this is the end of the study on "detailed explanation of JavaScript object-oriented programming", hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.