点击切换帐号登陆
帐号密码登陆

构造函数和原型的返回值(二)

2.自定义构造函数
==============

**知识点**
1. 内置构造函数
2. 自定义构造函数
3. 构造函数的原型
4. 构造函数返回值

-------------------------------------------------------

1.内置构造函数
-----------
1. 内置构造函数: Number()/String/Boolean/Array/Date/Object/...
2. 直接使用,接受传参创建数据
3. 数量和功能都是非常有限的

--------------------------------------------------------

2.自定义构造函数
--------------
1. 基本的命名方法
2. 内部this的指向
3. 调用方式: new
4. 新对象生成原理:
    1. 创建一个空对象并且this指向这个新对象,同时继承了该函数的原型属性
    2. 自定义的属性和方法添加到这个新对象中
    3. 使用this,返回这个新对象

以下是一个示例, 其中1和3是不需要也不应该出现在构造函数中,这里只是演示原理的需要:

```js
var Person = function (name) {
    // 1. 隐式代码
    var this = {};
    
    // 2. 向this添加属性
    this.name = name;
    this.getName = function () {
        return this.name;
    };
    
    // 3. 返回新对象: this
    return this;
}
```

--------------------------------------------------------------------

3.构造函数的原型
--------------
将构造函数中的方法添加到原型对象中,实现方法共享

--------------------------------------------------------------------

4.构造函数返回值
-------------
- 默认返回新创建的对象, 由this引用
- 可以改变返回的对象
- 如果返回的是非对象类型,则忽略,仍使用this引用的对象

--------------------------------------------------------------------

### 示例源码: code/demo02.html

```html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>构造函数</title>
</head>
<body>
<script>
    // 使用字面量创建构造函数
    var Person = function (name, email) {
        this.name = name;
        this.email = email;
        this.getInfo = function () {
            return this.name + '的邮箱是: ' + this.email;
        }
    };

    var person1 = new Person('admin', 'admin@0133.cn');
    console.log(person1.getInfo());

    var person2 = new Person('peter', 'peter@0133.cn');
    console.log(person2.getInfo());

    // 其实每个对象中,有区别是属性,而方法基本上是不变的,为了防止每次实例化时重复生成方法函数
    //应该将方法添加到构造函数的原型对象中, 这样就可以被所有对象所共享

    var Person = function (name, email) {
        this.name = name;
        this.email = email;
    };

    // 将构造函数中的方法添加到原型对象中,实现方法共享
    Person.prototype.getInfo = function () {
        return this.name + '的邮箱是: ' + this.email;
    };

    var person1 = new Person('admin', 'admin@0133.cn');
    console.log(person1.getInfo());

    var person2 = new Person('peter', 'peter@0133.cn');
    console.log(person2.getInfo());

    //构造函数的返回类型
    var Animal= function (name) {
        this.name = name;
        this.getName = function () {
            return this.name;
        };
        // return this;  // 狗
        var that = {};
        that.name = '猪';
        that.getName = function () {
            return that.name;
        };

        // return that;    // 猪
        return '0133.cn';    // 猪

    };

    var animal = new Animal('狗');
    console.log(animal.getName());  // 可以在构造函数中返回任何对象,不一定是必须是this

    //如果返回的不是对象类型,将忽略返回值, 仍将原来的this对象返回
</script>
</body>
</html>
```


任务

?不会了怎么办
无数据提示暂无评论哟...我要评论
网站导航
标签地图
学习路径
视频教程
开发软件
旗下子站
php中文网
phpstudy
技术文章
文档工具
关于我们
企业合作
人才招聘
联系我们
讲师招募
QQ交流群
QQ官方交流群
微信公众号
微信公众号