[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
[JavaScript基础]学习②⑤--创建对象_第1张图片
Paste_Image.png
xiaoming.name; // '小明'
xiaohong.name; // '小红'
xiaoming.hello; // function: Student.hello()
xiaohong.hello; // function: Student.hello()
xiaoming.hello === xiaohong.hello; // false

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

[JavaScript基础]学习②⑤--创建对象_第2张图片
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('测试失败!');
}

你可能感兴趣的:([JavaScript基础]学习②⑤--创建对象)