Home > Article > Web Front-end > Review of Javascript basics (3) js object-oriented
Originally, I was going to continue the last article in the series of expressions from simple to deep, but recently the team has suddenly become busy, busier than ever before! But friends who like expressions, don't worry, I'm already writing it :) At work, I found that everyone has a little understanding of some basic principles of Javascript here or there, so I decided to spend some time sorting out these basic knowledge and share them with everyone. A PPT for training will be attached later. At first I planned to write one article, but as I continued writing, I found more and more, so I decided to write a series. All the content in this series involves the basics of Javascript, and there is no fancy stuff, but I believe these basic things will help you understand the interesting things.
This article is the third article in the Javascript series you must know. We mainly look at how Javascript is object-oriented programming. Mainly involves the following content:
Objects in Javascript
What is an object
Traversing properties
Creating objects
Factory pattern
Constructor pattern
Detailed explanation of this
In function
In object method
In constructor
In call and apply
In bind
In the dom element event handling function
Detailed explanation of prototype
What is a prototype
What is the prototype chain
Using the prototype chain to implement inheritance
Problems in the prototype chain
Objects in Javascript
What is an object
We can understand objects in Javascript as a set of unordered key-value pairs, just like Dictionary8705e7b0a0f0c2904aabf05142ed2907 in C#. Key is the name of the attribute, and value can be of the following three types:
Basic value (string, number, boolean, null, undefined)
Object
Function
var o = new Object(); o["name"] = "jesse"; //基本值作为对象属性 o["location"] = { //对象作为对象属性 "city": "Shanghai", "district":"minhang" }; // 函数 作为对象属性 o["sayHello"] = function () { alert("Hello, I am "+ this.name + " from " + this.location.city); } o.sayHello();
Traversing properties
In C# we can use foreach to traverse Dictionary8705e7b0a0f0c2904aabf05142ed2907. If the object is a set of key-value pairs in Javascript If so, how do we traverse it?
for (var p in o) { alert('name:'+ p + ' type:' + typeof o[p] ); } // name:name type:string // name:location type:object // name:sayHello type:function
The above traversal method will also include the attributes in the prototype. We will talk about what a prototype is and how to distinguish the attributes in the prototype and the instance below.
Creating Objects
In fact, we have created an object above and used the following two ways to create objects.
Use new to create an instance of Object.
Literal
Our o above was created in the first way, and the location attribute in o was created in a literal way. The first method actually has a name called constructor pattern, because Object is actually a constructor, which generates an instance of Object for us. If you are still unclear about the constructor, hurry up and read my first article Type Basics Object and Object.
In addition to the above two methods, let’s also take a look at some of our ways to create objects:
Factory pattern
function createPerson(name, age, job){ var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function(){ alert(this.name); }; return o; } var person1 = createPerson('Jesse', 29, 'Software Engineer'); var person2 = createPerson('Carol', 27, 'Designer');
This kind There is a problem with the object created by the pattern, that is, it creates an instance of Object for me inside the function. This instance has nothing to do with our constructor createPerson.
Because I created this object internally using new Object(), it is an instance of Object. So if we want to know which function it is an instance of, it's impossible.
Constructor Pattern
The factory pattern does not solve the problem of object identification, but we can think about it. Object() is actually a function, but when I add a new in front of it , it becomes a constructor to generate an instance of Object for us. Then I can also add new in front of other functions to generate an instance of this function. This is the so-called constructor pattern.
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.sayName = function(){ alert(this.name); }; } var p1 = new Person('Jesse', 18, 'coder'); alert(p1 instanceof Person); // true
Detailed explanation of this
This can also be regarded as a very magical object in Javascript. Yes, this is an object. We talked about variable objects in the previous article Scope and Scope Chain. The variable object determines which properties and functions can be accessed in the current execution environment. To a certain extent, we can use this Think of it as this variable object. We mentioned before that the largest execution environment is the global execution environment, and window is the variable object in the global execution environment, so if we use this===window in the global environment, it will return true.
In addition to the global execution environment, we also mentioned another execution environment, which is a function. Each function has a this object, but sometimes the values they represent are different, mainly determined by the caller of this function. Let’s take a look at the following scenarios:
Function
function f1(){ return this; } f1() === window; // global object
因为当前的函数在全局函数中运行,所以函数中的this对象指向了全局变量对象,也就是window。这种方式在严格模式下会返回undefined。
对象方法
var o = { prop: 37, f: function() { return this.prop; } }; console.log(o.f()); // logs 37
在对象方法中,this对象指向了当前这个实例对象。注意: 不管这个函数在哪里什么时候或者怎么样定义,只要它是一个对象实例的方法,那么它的this都是指向这个对象实例的。
var o = { prop: 37 }; var prop = 15; function independent() { return this.prop; } o.f = independent; console.log(independent()); // logs 15 console.log(o.f()); // logs 37
区别:上面的函数independent如果直接执行,this是指向全局执行环境,那么this.prop是指向我们的全局变量prop的。但是如果将independent设为对象o的一个属性,那么independent中的this就指向了这个实例,同理this.prop就变成了对象o的prop属性。
构造函数
我们上面讲到了用构造函数创建对象,其实是利用了this的这种特性。在构造函数中,this对象是指向这个构造函数实例化出来的对象。
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function () { alert(this.name); }; } var p1 = new Person('Jesse', 18, 'coder'); var p2 = new Person('Carol',16,'designer');
当我们实例化Person得到p1的时候,this指向p1。而当我们实例化Person得到p2的时候,this是指向p2的。
利用call和apply
当我们用call和apply去调用某一个函数的时候,这个函数中的this对象会被绑定到我们指定的对象上。而call和apply的主要区别就是apply要求传入一个数组作为参数列表。
function add(c, d) { return this.a + this.b + c + d; } var o = { a: 1, b: 3 }; // 第一个参数会被绑定成函数add的this对象 add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16 // 第二个参数是数组作为arguments传入方法add add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
在bind方法中
bind方法是 存在于function的原型中的 Function.prototype.bind,也就是说所有的function都会有这个方法。但我们调用某一个方法的bind的时候,会产生一个和原来那个方法一样的新方法,只不过this是指向我们传得bind的第一个参数。
function f() { return this.a; } var g = f.bind({ a: "azerty" }); console.log(g()); // azerty var o = { a: 37, f: f, g: g }; console.log(o.f(), o.g()); // 37, azerty
在dom元素事件处理器中
在事件处理函数中,我们的this是指向触发这个事件的dom元素的。
HTML代码
<html> <body> <div id="mydiv" style="width:400px; height:400px; border:1px solid red;"></div> <script type="text/javascript" src="essence.js"></script> </body> </html>
JavaScript代码
function click(e) { alert(this.nodeName); } var myDiv = document.getElementById("mydiv"); myDiv.addEventListener('click', click, false);
当我们点击页面那个div的时候,毫无疑问,它是会显示DIV的。
详解prototype
prototype即原型,也是Javascrip中一个比较重要的概念。在说原型之前呢,我们需要回顾一下之前的构造函数模式。在我们用构造函数去创建对象的时候主要是利用了this的特性。
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; this.sayName = function () { alert(this.name); }; } var p1 = new Person('Jesse', 18, 'coder'); var p2 = new Person('Carol', 17, 'designer');
我们上面还讲到了当用Person实例化p1的时候Person中的this是指向p1的,当实例化p2的时候呢,this是指向p2的。那也就是说,p1和p2中的sayName虽然起到了同样的作用,但是实际上他们并非是一个函数。
也就是说他们内存堆中是存在多份拷贝的,而不是在栈中引用地址的拷贝。先不说这符不符合面向对象的思想,至少这对于内存来说也是一种浪费。而解决办法就是我们要讨论的原型。
什么是原型
在Javascript中的每一个函数,都会有一个原型对象,这个原型对象和我们普通的对象没有区别。只不过默认会有一个constructor属性指向这个函数。 同时,所有这个函数的实例都会有一个引用指向这个原型对象。如果不太清楚,那就看看下面这张图吧:
以上就是构造函数,构造函数原型,以及实例之间的关系。以我们的Person构造函数为例,所有Person的实例(p1,p2)都舒服一个prototype属性指向了Person构造函数prototype对象。如此一来,我们就可以把方法写在原型上,那么我们所有的实例就会访问同一个方法了。
function Person(name, age, job) { this.name = name; this.age = age; this.job = job; Person.prototype.sayName = function () { alert(this.name); } } var p1 = new Person('Jesse', 18, 'coder'); var p2 = new Person('Carol', 17, 'designer'); alert(p1.sayName == p2.sayName); // true
什么是原型链
大家还记得作用域链么?如果不记得,请自觉到第二篇中去复习(作用域和作用域链)。简单的来说,我们在一个执行环境中访问某个变量的时候如果当前这个执行环境中不存在这个变量,那么会到这个执行环境的包含环境也就是它的外层去找这个变量,外层还找不到那就再外一层,一直找到全局执行环境为止,这就是作用域链。而原型链有点类型,只不过场景换到了我们的对象实例中,如果我在一个实例中找某一个属性,这个实例中没有,那就会到它的原型中去找。记住,我们上面说了,原型也是一个对象,它也有自己的原型对象,所以就行成了一个链,实例自己的原型中找不到,那就到原型的原型对象中去找,一直向上延伸到Object的原型对象,默认我们创建的函数的原型对象它自己的原型对象是指向Object的原型对象的,所以这就是为什么我们可以在我们的自定义构造函数的实例上调用Object的方法(toString, valueOf)。
利用原型实现继承
其实我们上面已经讲了继承在Javascript中的实现,主要就是依靠原型链来实现的。所有的实例是继承自object就是因为在默认情况下,我们所有创建函数的原型对象的原型都指向了object对象。同理,我们可以定义自己的继承关系。
function Person(name, age, job) { this.name = name; this.age = age; } Person.prototype.sayName = function () { alert(this.name); } function Coder(language){ this.language = language; } Coder.prototype = new Person(); //将 Coder 的原型指向一个Person实例实现继Person Coder.prototype.code = function () { alert('I am a '+ this.language +' developer, Hello World!'); } function Designer() { } Designer.prototype = new Person(); //将 Desiger 的原型指向一个Person实例实现继Person Designer.prototype.design = function () { alert('其实我只是一个抠图工而已。。。。'); } var coder = new Coder('C#'); coder.name = 'Jesse'; coder.sayName(); //Jesse coder.code(); // I am a C# developer, Hello World! var designer = new Designer(); designer.name = 'Carol'; designer.sayName(); // Carol designer.design(); // 其实我只是一个抠图工而已。。。。
原型链中的问题
由于原型对象是以引用的方式保存的,所以我们在赋值的时候要特别注意,一不小心就有可能把之前赋的值给赋盖了。比如上面的代码中,我们先写原型方法,再实现继承,那我们的原型方法就没有了。
function Coder(language){ this.language = language; } Coder.prototype.code = function () { alert('I am a '+ this.language +' developer, Hello World!'); } Coder.prototype = new Person(); //这里会覆盖上面所有的原型属性和方法 var coder = new Coder('C#'); coder.name = 'Jesse'; coder.sayName(); coder.code(); // 这里会报错,找不到code方法。
这样三篇文章都完成了
更多Javascript基础回顾之(三) js面向对象相关文章请关注PHP中文网!