JS面向对象笔记二

菜单导航,《JS面向对象笔记一》,  参考书籍:阮一峰之《JavaScript标准参考教程》

一、构造函数和new命令

二、this关键字

三、构造函数和new命令

四、构造函数和new命令

五、构造函数和new命令

六、构造函数和new命令

七、构造函数和new命令

八、构造函数和new命令

一、构造函数和new命令

1、构造函数

  • JavaScript语言的对象体系,不是基于“类”的,而是基于构造函数(constructor)和原型链(prototype)
  • 为了与普通函数区别,构造函数名字的第一个字母通常大写,比如:  var Person = function(){  this.name = ‘王大锤‘;  }
  • 构造函数的特点: 
           a、函数体内部使用了this关键字,代表了所要生成的对象实例;
       b、生成对象的时候,必需用new命令调用此构造函数

2、new

  作用:就是执行构造函数,返回一个实例对象 

var Person = function(name, age){
    this.name = name;
    this.age = age;
    this.email = ‘[email protected]‘;
    this.eat = function(){
        console.log(this.name + ‘ is eating noodles‘);
    }
}

var per = new Person(‘王大锤‘, 18);
console.log(per.name + ‘, ‘ + per.age + ‘, ‘ + per.email); //王大锤, 18, [email protected]
per.eat();  //王大锤 is eating noodles

执行new命令时的原理步骤:

  1. 创建一个空对象,作为将要返回的对象实例
  2. 将这个空对象的原型,指向构造函数的prototype属性
  3. 将这个空对象赋值给函数内部的this关键字
  4. 开始执行构造函数内部的代码

注意点:当构造函数里面有return关键字时,如果返回的是非对象,new命令会忽略返回的信息,最后返回时构造之后的this对象;
  如果return返回的是与this无关的新对象,则最后new命令会返回新对象,而不是this对象。示例代码:

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

如果调用构造函数的时候,忘记使用new关键字,则构造函数里面的this为全局对象window,属性也会变成全局属性,

则被构造函数赋值的变量不再是一个对象,而是一个未定义的变量,js不允许给undefined添加属性,所以调用undefined的属性会报错。

示例:

var Person = function(){
    console.log( this == window );  //true
    this.price = 5188;
}
var per = Person();
console.log(price); //5188
console.log(per);  //undefined
console.log(‘......_-_‘); //......_-_
console.log(per.price); //Uncaught TypeError: Cannot read property ‘helloPrice‘ of undefined

为了规避忘记new关键字现象,有一种解决方式,就是在函数内部第一行加上 : ‘use strict‘;

表示函数使用严格模式,函数内部的this不能指向全局对象window, 默认为undefined, 导致不加new调用会报错

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

var per = Person(); 

另外一种解决方式,就是在函数内部手动添加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

二、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: ‘[email protected]‘,
    name: ‘赵日天‘,
    eat: function(){
        console.log(this);
    }
}

console.log(Employ.email + ‘, ‘ + Employ.name);
Employ.eat();
/* 打印日志:
---------------
[email protected], 赵日天
Object {email: "[email protected]", name: "赵日天", eat: function}
*/

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

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}
*/

示例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变量,则为undefined
            console.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指的是对象obj
            console.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
 */

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.....
*/

时间: 2024-08-04 23:27:25

JS面向对象笔记二的相关文章

js面向对象编程(二) 构造函数继承

构造函数绑定 //基类建筑物var building = function () {    this.spec = "building";}; //address:房子地址,toward:房子朝向var house = function (address, toward) {    this.address = address;    this.toward = toward;}; //使房子继承建筑物 //使用call或者apply方法,将父对象的构造函数绑定在子对象上,在子对象构造

JS面向对象(二)---继承

一.面向对象的继承 1.解析:在原有对象的基础上,略作修改,得到一个新的对象,并且不影响原有对象的功能 2.如何添加继承---拷贝继承 属性:call 方法: for in /* 继承:子类不影响父类,子类可以继承父类的一些功能(代码复用) 属性的继承:调用父类的构造1函数 call 方法的继承:for in 拷贝继承 */ //父类 function CreatePerson(name,sex){ this.name = name; this.sex = sex; } CreatePerson

【转】require.js学习笔记(二)

require.js遵循AMD规范,通过define定义模块,require异步加载模块,一个js文件即一个模块. 一.模块加载require1.加载符合AMD规范模块 HTML: <script src="js/require.js" data-main="js/main"></script> MAIN.JS require.config({ baseUrl: "js/lib", paths: { "jquer

[转]node.js学习笔记(二)

二.express 1.安装 express4 npm --registry=http://registry.npmjs.org install -g express-generator (全局) 2.新建express项目 express -t ejs newsproject cd newsproject npm --registry=http://registry.npmjs.org install 3.启动项目 A 修改app.js增加 其中,通过app.use('/',routes)访问

vue.js学习笔记(二):如何加载本地json文件

在项目开发的过程中,因为无法和后台的数据做交互,所以我们可以自建一个假数据文件(如data.json)到项目文件夹中,这样我们就可以模仿后台的数据进行开发.但是,如何在一个vue.js 项目中引入本地的json文件呢,下面就将步骤贴出来.(此时项目是由webpack打包而成). 整个项目是由webpack打包而成,具体步骤上网查找.具体项目结构如下: 1:我们找到bulid>dev-server.js,然后打开 2:在里面加入这段代码. var app = express() var appDa

JS面向对象笔记

0.匿名函数定以后直接调用:(function(numA, numB) { alert(numA + numB); })(3,4);//弹窗7 1.js中函数就是对象,对象就是函数.arguments表示函数的参数集合 2.js中方法直接调用为函数,用new调用为对象.JavaScript中没有类的语法,是用函数闭包模拟出来的 3.js中给对象动态添加属性示例: //定义一个函数 function Person(){ } //1.直接调用函数名,就只是单纯的表示调用函数 Person(); //

node.js学习笔记二之版本问题

一.版本说明 进入node.js官网https://nodejs.org/en/download/ 点击上面的[All download options]进入到所有下载列表的地址 下载地址:https://nodejs.org/dist/ 0.是Joyent公司维护.进展缓慢.但是稳定. 4.,5.*都是由网友维护的.相对的进展快,增加和许多新功能. 偶数开头的是稳定版,奇数开头的开发版就是会不断变化更新.为下一个稳定版本做测试差不多的意思. 不过现在都是在nodejs基金会下面.所以咱们在no

js面向对象(二)——继承

上一篇随笔讲了封装,这一篇我们说说继承,还是那上一篇猫和狗说事儿 function Dog(name,s){ this.name=name; this.sex=s; } Dog.prototype.type="犬科"; Dog.prototype.spack==function(){ alert("汪汪..."); } function Cat(name,s){ this.name=name; this.sex=s; } Cat.prototype.type=&qu

JS面向对象篇二、什么是原型?原型对象与实例对象、构造函数的关系及相关方法

本文内容: 1.构造函数.原型对象与实例对象之间的关系: 2.isPrototypeOf()和Object.getPrototypeOf(); 3.实例对象上与原型对象上同名的属性处理: 4.hasOwnProperty()方法和in操作符判断属性来自实例对象本身还是它的原型对象: 5.for-in.Object.keys()和Object.getOwnPropertyNames()方法获取实例对象或者原型对象上的属性: 6.需注意的特殊问题 构造函数.原型对象与实例对象 function Pe