实例对象与new命令

最近学习:实例对象与new命令

JavaScript语言的对象体系,是基于构造函数(constructor)和原型链(prototype)。
构造函数就是一个普通的函数,但有自己的特征和用法。构造函数名字的第一个字母通常大写。

var Vehicle = function () {
this.price = 1000;
};

构造函数特点:
1、函数体内部使用了this
2、生成对象的时候,必须使用new命令

//-------------------------------------------
var Vehicle = function () {
this.price = 1000;
};
var v = new Vehicle();
v.price // 1000
//-------------------------------------------
var Vehicle = function (p) {
this.price = p;
};
var v = new Vehicle(500);
//-------------------------------------------

为了保证构造函数必须与new命令一起使用,

一个解决办法是,构造函数内部使用严格模式,即第一行加上 'use strict'; 。
这样的话,一旦忘了使用new命令,直接调用构造函数就会报错。

function Fubar(foo, bar){
'use strict';
this._foo = foo;
this._bar = bar;
}
Fubar()
// TypeError: Cannot set property '_foo' of undefined

另一个解决办法,构造函数内部判断是否使用new命令,如果发现没有使用,则直接返回一个实例对象。

function Fubar(foo, bar) {
if (!(this instanceof Fubar)) {
return new Fubar(foo, bar);
}
this._foo = foo;
this._bar = bar;
}
Fubar(1, 2)._foo // 1
(new Fubar(1, 2))._foo // 1

注:getMessage是一个普通函数,返回一个字符串。对它使用new命令,会得到一个空对象。

function getMessage() {
return 'this is a message';
}
var msg = new getMessage();
msg // {}
typeof msg // "object"

构造原理:new命令简化的内部流程,可以用下面的代码表示。

function _new(/* 构造函数 */ constructor, /* 构造函数参数 */ params) {
// 将 arguments 对象转为数组
var args = [].slice.call(arguments);
// 取出构造函数
var constructor = args.shift();
// 创建一个空对象,继承构造函数的 prototype 属性
var context = Object.create(constructor.prototype);
// 执行构造函数
var result = constructor.apply(context, args);
// 如果返回结果是对象,就直接返回,否则返回 context 对象
return (typeof result === 'object' && result != null) ? result : context;
}
// 实例
var actor = _new(Person, '张三', 28);

new.target
函数内部可以使用 new.target 属性。如果当前函数是new命令调用,new.target指向当前函数,否则为undefined。

function f() {
console.log(new.target === f);
}
f() // false
new f() // true
使用这个属性,可以判断函数调用的时候,是否使用new命令。
function f() {
if (!new.target) {
throw new Error('请使用 new 命令调用!');
}
// ...
}
f() // Uncaught Error: 请使用 new 命令调用!

Object.create() 创建实例对象
构造函数作为模板,可以生成实例对象。但是,有时拿不到构造函数,只能拿到一个现有的对象。我们希望以这个现有的对象作为模板,生成新的实例对象,这时就可以使用 Object.create() 方法。

var person1 = {
name: '张三',
age: 38,
greeting: function() {
console.log('Hi! I\'m ' + this.name + '.');
}
};
var person2 = Object.create(person1);
person2.name // 张三
person2.greeting() // Hi! I'm 张三.

上面代码中,对象person1是person2的模板,后者继承了前者的属性和方法。

 

posted @ 2020-08-26 13:57  小清秋  阅读(174)  评论(0编辑  收藏  举报