[JavaScript基础]学习②⑤--创建对象

var arr = [1, 2, 3];

其原型链是

arr ----> Array.prototype ----> Object.prototype ----> null

Array.prototype定义了indexOf()、shift()等方法

function foo() {
    return 0;
}

原型链是

foo ----> Function.prototype ----> Object.prototype ----> null

Function.prototype定义了apply()等方法

构造函数

定义

function Student(name) {
    this.name = name;
    this.hello = function () {
        alert('Hello, ' + this.name + '!');
    }
}

用关键字new来调用这个函数,并返回一个对象

var xiaoming = new Student('小明');
xiaoming.name; // '小明'
xiaoming.hello(); // Hello, 小明!

如果不写new,这就是一个普通函数,它返回undefined

原型链

xiaoming ----> Student.prototype ----> Object.prototype ----> null
Paste_Image.png

用new Student()创建的对象还从原型上获得了一个constructor属性,它指向函数Student本身

xiaoming.constructor === Student.prototype.constructor; // true
Student.prototype.constructor === Student; // true

Object.getPrototypeOf(xiaoming) === Student.prototype; // true

xiaoming instanceof Student; // true
Paste_Image.png
xiaoming.name; // '小明'
xiaohong.name; // '小红'
xiaoming.hello; // function: Student.hello()
xiaohong.hello; // function: Student.hello()
xiaoming.hello === xiaohong.hello; // false

让创建的对象共享一个hello函数

Paste_Image.png
function Student(name) {
    this.name = name;
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};

构造函数首字母应当大写,而普通函数首字母应当小写

常用的编程模式

function Student(props) {
    this.name = props.name || '匿名'; // 默认值为'匿名'
    this.grade = props.grade || 1; // 默认值为1
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};

function createStudent(props) {
    return new Student(props || {})
}

优点:new来调用
参数灵活,可以不传

var xiaoming = createStudent({
    name: '小明'
});

xiaoming.grade; // 1

练习

'use strict';
function Cat(name) {
    this.name=name;
}

Cat.prototype.say=function(){
   return 'Hello, '+this.name+'!';
}

// 测试:
var kitty = new Cat('Kitty');
var doraemon = new Cat('哆啦A梦');
if (kitty && kitty.name === 'Kitty' && kitty.say && typeof kitty.say === 'function' && kitty.say() === 'Hello, Kitty!' && kitty.say === doraemon.say) {
    alert('测试通过!');
} else {
    alert('测试失败!');
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • avaScript对每个创建的对象都会设置一个原型,指向它的原型对象。 当我们用obj.xxx访问一个对象的属性时...
    源大侠阅读 2,144评论 0 1
  • 本文是大神廖雪峰的JavaScript教程学习笔记。并不是教程,如有需要,请前往廖雪峰大神大博客. JavaScr...
    0o冻僵的企鹅o0阅读 2,675评论 0 0
  • JavaScript 快速入门 面向对象编程创建对象构造函数忘记写new怎么办?原型继承class继承 面向对象编...
    染微言阅读 1,823评论 0 0
  • 面向对象(Object-Oriented,OO)的语言有一个标志,那就是它们都有类的慨念,而通过类可以创建任意多个...
    threetowns阅读 4,355评论 0 4
  • 姓名:钱嘉露书名《啊笨猫和外星小贩》读书心得: 今天,我读了一本书,名叫《阿笨猫和外星小贩》。 这本书主要讲阿笨猫...
    嘉露阅读 1,769评论 0 0

友情链接更多精彩内容