JavaScript 语言的对象体系,不是基于“类”的,而是基于构造数`constructor`和原型链`prototype`, 因此JS 专门使用构造函数做为对象模板 ,一个构造函数,可生成多个实列对象,它们有相同的结构html
//constructor var Bird = function () { this.name = 'lai fu'; }; var bird1 = new Bird(); // 也可使用 new Bird; 推荐使用前者 console.log(bird1.name) // "lai fu" //ordinary var a =Bird(); console.log(a) // undefined console.log(a.name) // typeError name // 'laifu'
//使用 严格模式 function Fubar(foo, bar){ 'use strict'; this._foo = foo; this._bar = bar; } Fubar()// TypeError //判断 this 不是构造函数(constructor)的实列对象 那么手动返回自身constructor function Far(a){ if (!(this instanceof Far)) return new Far(a); this._a=a; } Far(1)._a
/** *新生成一个空对象 *连接到原型 *绑定 this *返回新对象 **/ function _new(constuctor,param) { // 得到构造函数 let Con = [].shift.call(arguments); // 连接到原型 let obj = Object.create(Con.prototype); // 绑定 this,执行构造函数 let result = Con.apply(obj, arguments) // 确保 new 出来的是个对象 return (typeof(result) === 'object' && result != null) ? result : obj } var fn = _new( function Person (name,age){ this.name = name; this.age = age }, 'Owen', 28); fn.name // 'Owen'
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 命令调用!
- 原始的对象以字典结构保存,每个属性名都对应一个属性描述对象。编程
var obj = { name: "Owen" }; { name: { [[value]]: "Owen" //函数的地址 [[writable]]: true //是否可赋值 [[enumerable]]: true//是否可枚举 [[configurable]]: true//是否可配置 } } //属性的值保存在属性描述对象的value属性里面。
若是 a 属性的值是 引用值 那么属性将如下面的形式保存的:数组
var obj = { fn: function () {} }; /* { fn: { [[value]]: [[writable]]: true [[enumerable]]: true [[configurable]]: true } } */
var f n= function () {}; var obj = { f: fn }; // 单独执行 fn() // obj 环境执行 obj.f()
(obj.fn = obj.fn)() // window // 等同于 (function () { console.log(this); })() (false || obj.fn)() // window // 等同于 (false || function () { console.log(this); })() (4, obj.fn)() // window // 等同于 (4, function () { console.log(this); })()
var o = { v: 'hello', p: [ 'Owen', 18 ], f: function f() { this.p.forEach(function (item) { console.log(this.v + '-' + item); }, this); //将外层的this传递给forEach方法 } } o.f() // hello-Owen hello-18