search
HomeWeb Front-endJS TutorialDetailed introduction to JS object-oriented (2)
Detailed introduction to JS object-oriented (2)Jun 29, 2017 pm 01:37 PM
javascriptobjectnotes

Menu Navigation, "JS Object-Oriented Notes 1", Reference book: Ruan Yifeng's "JavaScript Standard Reference Tutorial"

1. Constructor and new command

2. this keyword

3. Constructor and new command

##4.Constructor and new command

5. Constructor and new command

6. Constructor and new command

7. Construction Function and new command

8. Constructor and new command

1. Constructor and new command

1. Constructor

  • The object system of JavaScript language is not based on "class", but based on constructor (constructor) and prototype chain (prototype)

  • In order to distinguish it from ordinary functions, the first letter of the constructor name is usually capitalized, for example: var Person = function(){ this.name = '王大 hammer'; }

  • Characteristics of the constructor:

    a. The
    this keyword is used inside the function body, which represents the object instance to be generated; b. The generated object When, you must use the
    new command to call this constructor

2. new

Function: It is to execute the constructor and return an instance object

var Person = function(name, age){this.name = name;this.age = age;this.email = 'cnblogs@sina.com';this.eat = function(){
        console.log(this.name + ' is eating noodles');
    }
}var per = new Person('王大锤', 18);
console.log(per.name + ', ' + per.age + ', ' + per.email); //王大锤, 18, cnblogs@sina.comper.eat();  //王大锤 is eating noodles
Principle steps when executing the new command:

  1. Create an empty object as the object instance to be returned

  2. Point the prototype of this empty object to the

    prototype attribute of the constructor

  3. Assign this empty object to

    this## inside the function #Keywords

  4. Start executing the code inside the constructor
  5. Note: When there is a return keyword in the constructor, if the returned If it is a non-object, the new command will ignore the returned information, and finally return the this object after construction;
If return returns a new object that has nothing to do with this, then the new command will return the new object instead of this object. Sample code:


console.log('---- 返回字符串 start ----');var Person = function(){this.name = '王大锤';return '罗小虎';
}var per = new Person();for (var item in per){
    console.log( item + ': ' + per[item] );
}//---- 返回字符串 start ----//name: 王大锤console.log('----- 返回对象 start ----');var PersonTwo = function(){this.name = '倚天剑';return {nickname: '屠龙刀', price: 9999 };
}var per2 = new PersonTwo();for (var item in per2){
    console.log(item + ': ' + per2[item]);
}//----- 返回对象 start ----//nickname: 屠龙刀//price: 9999
View Code

If you forget when calling the constructor Using the new keyword, this in the constructor is the global object window, and the properties will also become global properties.

The variable assigned by the constructor is no longer an object, but an undefined variable , js does not allow adding attributes to undefined, so calling undefined attributes will report an error.

Example:

var Person = function(){ 
    console.log( this == window );  //truethis.price = 5188; 
}var per = Person();
console.log(price); //5188console.log(per);  //undefinedconsole.log('......_-_'); //......_-_console.log(per.price); //Uncaught TypeError: Cannot read property 'helloPrice' of undefined
View Code
In order to avoid forgetting the new keyword, there is A solution is to add: 'use strict';

to the first line inside the function, indicating that the function uses strict mode. This inside the function cannot point to the global object window, and the default is undefined, resulting in no new call. An error will be reported

var Person = function(){ 'use strict';
    console.log( this );  //undefinedthis.price = 5188; //Uncaught TypeError: Cannot set property 'helloPrice' of undefined}var per = Person();
View Code

另外一种解决方式,就是在函数内部手动添加new命令:

var Person = function(){ //先判断this是否为Person的实例对象,不是就new一个if (!(this instanceof Person)){return new Person();
    }
    console.log( this );  //Person {}this.price = 5188; 
}var per = Person(); 
console.log(per.price); //5188
View Code

 

 

二、this关键字

var Person = function(){
    console.log('1111'); 
    console.log(this); this.name = '王大锤';this.age = 18;this.run = function(){
        console.log('this is Person的实例对象吗:' + (this instanceof Person) ); 
        console.log(this); 
    }
}var per = new Person();
per.run();/* 打印日志:
1111
Person {}
this is Person的实例对象吗:true
Person {name: "王大锤", age: 18, run: function}*/console.log('---------------');var Employ = {
    email: 'cnblogs@sina.com',
    name: '赵日天',
    eat: function(){
        console.log(this);
    }
}

console.log(Employ.email + ', ' + Employ.name);
Employ.eat();/* 打印日志:
---------------
cnblogs@sina.com, 赵日天
Object {email: "cnblogs@sina.com", name: "赵日天", eat: function}*/
View Code

1、this总是返回一个对象,返回属性或方法当前所在的对象, 如上示例代码

2、对象的属性可以赋值给另一个对象,即属性所在的当前对象可变化,this的指向可变化

var A = { 
    name: '王大锤', 
    getInfo: function(){return '姓名:' + this.name;
    } 
}var B = { name: '赵日天' };

B.getInfo = A.getInfo;
console.log( B.getInfo() ); //姓名:赵日天//A.getInfo属性赋给B, 于是B.getInfo就表示getInfo方法所在的当前对象是B, 所以这时的this.name就指向B.name
View Code

 3、由于this指向的可变化性,在层级比较多的函数中需要注意使用this。一般来说,在多层函数中需要使用this时,设置一个变量来固定this的值,然后在内层函数中这个变量。

示例1:多层中的this

//1、多层中的this (错误演示)var o = {
    f1: function(){
        console.log(this); //这个this指的是o对象var f2 = function(){
            console.log(this);
        }();//由于写法是(function(){ })() 格式, 则f2中的this指的是顶层对象window    }
}

o.f1();/* 打印日志:
Object {f1: function}

Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}*///2、上面代码的另一种写法(相同效果)var temp = function(){
    console.log(this);
}var o = {
    f1: function(){
        console.log(this); //这个this指o对象var f2 = temp(); //temp()中的this指向顶层对象window    }
}
o.f1(); 
/* 打印日志
Object {f1: function}

Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}*///表示上面两种写法是一样的效果,this的错误演示//3、多层中this的正确使用:使用一个变量来固定this对象,然后在内层中调用该变量var o = {
    f1: function(){
        console.log(this); //o对象var that = this;var f2 = function(){
            console.log(that); //这个that指向o对象        }();
    }
}
o.f1();/* 打印日志:
Object {f1: function}
Object {f1: function}*/
View Code

示例2: 数组遍历中的this

//1、多层中数组遍历中this的使用 (错误演示)var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){//第一个this指的是obj对象this.arr.forEach(function(item){//这个this指的是顶层对象window, 由于window没有email变量,则为undefinedconsole.log(this.email + ': ' + item);
        });
    }
}

obj.fun(); 
/* 打印结果:
undefined: aaa
undefined: bbb
undefined: 333 *///2、多层中数组遍历中this的使用 (正确演示,第一种写法)var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){//第一个this指的是obj对象var that = this; //将this用变量固定下来this.arr.forEach(function(item){//这个that指的是对象objconsole.log(that.email + ': ' + item);
        });
    }
}
obj.fun(); //调用/* 打印日志:
大锤@sina.com: aaa
大锤@sina.com: bbb
大锤@sina.com: 333 *///3、多层中数组遍历中this正确使用第二种写法:将this作为forEach方法的第二个参数,固定循环中的运行环境var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){//第一个this指的是obj对象this.arr.forEach(function(item){//这个this从来自参数this, 指向obj对象console.log(this.email + ': ' + item);
        }, this);
    }
}
obj.fun(); //调用/* 打印日志:
大锤@sina.com: aaa
大锤@sina.com: bbb
大锤@sina.com: 333 */
View Code

 

4、关于js提供的call、apply、bind方法对this的固定和切换的用法

  1)、function.prototype.call(): 函数实例的call方法,可以指定函数内部this的指向(即函数执行时所在的作用域),然后在所指定的作用域中,调用该函数。
  如果call(args)里面的参数不传,或者为null、undefined、window, 则默认传入全局顶级对象window;
  如果call里面的参数传入自定义对象obj, 则函数内部的this指向自定义对象obj, 在obj作用域中运行该函数

var obj = {};var f = function(){
    console.log(this);return this;
}

console.log('....start.....');
f();
f.call();
f.call(null);
f.call(undefined);
f.call(window);
console.log('**** call方法的参数如果为空、null和undefined, 则默认传入全局等级window;如果call方法传入自定义对象obj,则函数f会在对象obj的作用域中运行 ****');
f.call(obj);
console.log('.....end.....');/* 打印日志:
....start.....
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
**** call方法的参数如果为空、null和undefined, 则默认传入全局等级window;如果call方法传入自定义对象obj,则函数f会在对象obj的作用域中运行 ****
Object {}
.....end.....*/
View Code

 

The above is the detailed content of Detailed introduction to JS object-oriented (2). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool