前端开发者进阶之ECMAScript新特性【一】--Object.create

 

Object.create(prototype, descriptors) :创建一个具有指定原型且可选择性地包含指定属性的对象

参数:
prototype 必需。  要用作原型的对象。 可以为 null。
descriptors 可选。 包含一个或多个属性描述符的 JavaScript 对象。
“数据属性”是可获取且可设置值的属性。 数据属性描述符包含 value 特性,以及 writable、enumerable 和 configurable 特性。

如果未指定最后三个特性,则它们默认为 false。 只要检索或设置该值,“访问器属性”就会调用用户提供的函数。 访问器属性描述符包含 set 特性和/或 get 特性。

var pt = {
say : function(){
console.log('saying!');
}
} var o = Object.create(pt); console.log('say' in o); // true
console.log(o.hasOwnProperty('say')); // false

如果prototype传入的是null,创建一个没有原型链的空对象。

var o1 = Object.create(null);
console.dir(o1); // object[ No Properties ]

当然,可以创建没有原型链的但带descriptors的对象;

var o2 = Object.create(null, {
size: {
value: "large",
enumerable: true
},
shape: {
value: "round",
enumerable: true
}
}); console.log(o2.size); // large
console.log(o2.shape); // round
console.log(Object.getPrototypeOf(o2)); // null

也可以创建带属性带原型链的对象:

var pt = {
        say : function(){
            console.log('saying!');   
        }
    } var o3 = Object.create(pt, {
size: {
value: "large",
enumerable: true
},
shape: {
value: "round",
enumerable: true
}
}); console.log(o3.size); // large
console.log(o3.shape); // round
console.log(Object.getPrototypeOf(o3)); // {say:...}

最重要的是实现继承,看下面实例:

//Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
} Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info("Shape moved.");
}; // Rectangle - subclass
function Rectangle() {
Shape.call(this); //call super constructor.
} Rectangle.prototype = Object.create(Shape.prototype); var rect = new Rectangle(); console.log(rect instanceof Rectangle); //true.
console.log(rect instanceof Shape); //true. rect.move(); //"Shape moved."

不支持浏览器的兼容实现:

1、简单实现,也是最常见的实现方式,没有实现第二个参数的功能:

if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
};
}

2、复杂实现,实现第二个参数的大部分功能:

if (!Object.create) {

    // Contributed by Brandon Benvie, October, 2012
var createEmpty;
var supportsProto = Object.prototype.__proto__ === null;
if (supportsProto || typeof document == 'undefined') {
createEmpty = function () {
return { "__proto__": null };
};
} else {
createEmpty = function () {
var iframe = document.createElement('iframe');
var parent = document.body || document.documentElement;
iframe.style.display = 'none';
parent.appendChild(iframe);
iframe.src = 'javascript:';
var empty = iframe.contentWindow.Object.prototype;
parent.removeChild(iframe);
iframe = null;
delete empty.constructor;
delete empty.hasOwnProperty;
delete empty.propertyIsEnumerable;
delete empty.isPrototypeOf;
delete empty.toLocaleString;
delete empty.toString;
delete empty.valueOf;
empty.__proto__ = null; function Empty() {}
Empty.prototype = empty;
// short-circuit future calls
createEmpty = function () {
return new Empty();
};
return new Empty();
};
} Object.create = function create(prototype, properties) { var object;
function Type() {} // An empty constructor. if (prototype === null) {
object = createEmpty();
} else {
if (typeof prototype !== "object" && typeof prototype !== "function") { throw new TypeError("Object prototype may only be an Object or null"); // same msg as Chrome
}
Type.prototype = prototype;
object = new Type(); object.__proto__ = prototype;
} if (properties !== void 0) {
Object.defineProperties(object, properties);
} return object;
};
}

前端开发者进阶之ECMAScript新特性【一】--Object.create

 

Object.create(prototype, descriptors) :创建一个具有指定原型且可选择性地包含指定属性的对象

参数:
prototype 必需。  要用作原型的对象。 可以为 null。
descriptors 可选。 包含一个或多个属性描述符的 JavaScript 对象。
“数据属性”是可获取且可设置值的属性。 数据属性描述符包含 value 特性,以及 writable、enumerable 和 configurable 特性。

如果未指定最后三个特性,则它们默认为 false。 只要检索或设置该值,“访问器属性”就会调用用户提供的函数。 访问器属性描述符包含 set 特性和/或 get 特性。

var pt = {
say : function(){
console.log('saying!');
}
} var o = Object.create(pt); console.log('say' in o); // true
console.log(o.hasOwnProperty('say')); // false

如果prototype传入的是null,创建一个没有原型链的空对象。

var o1 = Object.create(null);
console.dir(o1); // object[ No Properties ]

当然,可以创建没有原型链的但带descriptors的对象;

var o2 = Object.create(null, {
size: {
value: "large",
enumerable: true
},
shape: {
value: "round",
enumerable: true
}
}); console.log(o2.size); // large
console.log(o2.shape); // round
console.log(Object.getPrototypeOf(o2)); // null

也可以创建带属性带原型链的对象:

var pt = {
        say : function(){
            console.log('saying!');   
        }
    } var o3 = Object.create(pt, {
size: {
value: "large",
enumerable: true
},
shape: {
value: "round",
enumerable: true
}
}); console.log(o3.size); // large
console.log(o3.shape); // round
console.log(Object.getPrototypeOf(o3)); // {say:...}

最重要的是实现继承,看下面实例:

//Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
} Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info("Shape moved.");
}; // Rectangle - subclass
function Rectangle() {
Shape.call(this); //call super constructor.
} Rectangle.prototype = Object.create(Shape.prototype); var rect = new Rectangle(); console.log(rect instanceof Rectangle); //true.
console.log(rect instanceof Shape); //true. rect.move(); //"Shape moved."

不支持浏览器的兼容实现:

1、简单实现,也是最常见的实现方式,没有实现第二个参数的功能:

if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
};
}

2、复杂实现,实现第二个参数的大部分功能:

if (!Object.create) {

    // Contributed by Brandon Benvie, October, 2012
var createEmpty;
var supportsProto = Object.prototype.__proto__ === null;
if (supportsProto || typeof document == 'undefined') {
createEmpty = function () {
return { "__proto__": null };
};
} else {
createEmpty = function () {
var iframe = document.createElement('iframe');
var parent = document.body || document.documentElement;
iframe.style.display = 'none';
parent.appendChild(iframe);
iframe.src = 'javascript:';
var empty = iframe.contentWindow.Object.prototype;
parent.removeChild(iframe);
iframe = null;
delete empty.constructor;
delete empty.hasOwnProperty;
delete empty.propertyIsEnumerable;
delete empty.isPrototypeOf;
delete empty.toLocaleString;
delete empty.toString;
delete empty.valueOf;
empty.__proto__ = null; function Empty() {}
Empty.prototype = empty;
// short-circuit future calls
createEmpty = function () {
return new Empty();
};
return new Empty();
};
} Object.create = function create(prototype, properties) { var object;
function Type() {} // An empty constructor. if (prototype === null) {
object = createEmpty();
} else {
if (typeof prototype !== "object" && typeof prototype !== "function") { throw new TypeError("Object prototype may only be an Object or null"); // same msg as Chrome
}
Type.prototype = prototype;
object = new Type(); object.__proto__ = prototype;
} if (properties !== void 0) {
Object.defineProperties(object, properties);
} return object;
};
}

前端开发者进阶之ECMAScript新特性--Object.create的更多相关文章

  1. 前端开发者进阶之ECMAScript新特性【一】--Object.create

    Object.create(prototype, descriptors) :创建一个具有指定原型且可选择性地包含指定属性的对象 参数:prototype 必需.  要用作原型的对象. 可以为 nul ...

  2. iOS8 针对开发者所拥有的新特性汇总如下

    iOS8 针对开发者所拥有的新特性汇总如下 1.支持第三方键盘 2.自带网页翻译功能(即在线翻译) 3.指纹识别功能开放:第三方软件可以调用 4.Safari浏览器可直接添加新的插件. 5.可以把一个 ...

  3. ECMAScript新特性【一】--Object.create

    Object.create(prototype, descriptors) :创建一个具有指定原型且可选择性地包含指定属性的对象 参数: prototype 必需.  要用作原型的对象. 可以为 nu ...

  4. 前端入门21-JavaScript的ES6新特性

    声明 本篇内容全部摘自阮一峰的:ECMAScript 6 入门 阮一峰的这本书,我个人觉得写得挺好的,不管是描述方面,还是例子,都讲得挺通俗易懂,每个新特性基本都还会跟 ES5 旧标准做比较,说明为什 ...

  5. 21、前端知识点--html5和css3新特性汇总

    跳转到该链接 新特性汇总版: https://www.cnblogs.com/donve/p/10697745.html HTML5和CSS3的新特性(浓缩好记版) https://blog.csdn ...

  6. 前端神器 Firebug 2.0 新特性一览

    如果你从事Web前端方面的开发工作,那么对Firebug一定不会陌生,这是Firefox浏览器的一款插件,集HTML查看和编辑.Javascript控制台.网络状况监视器于一体,给Web开发者带来了极 ...

  7. 前端开发者进阶之函数柯里化Currying

    穆乙:http://www.cnblogs.com/pigtail/p/3447660.html 在计算机科学中,柯里化(英语:Currying),又译为卡瑞化或加里化,是把接受多个参数的函数变换成接 ...

  8. 前端(七):ES6一些新特性

    一.变量 1.var关键字的弊端 var关键字的弊端:1.可以重复声明变量:2.无法限制变量修改:3.没有块级作用域,只有函数作用域. <html lang="en"> ...

  9. 前端开发者进阶之函数反柯里化unCurrying

    函数柯里化,是固定部分参数,返回一个接受剩余参数的函数,也称为部分计算函数,目的是为了缩小适用范围,创建一个针对性更强的函数. 那么反柯里化函数,从字面讲,意义和用法跟函数柯里化相比正好相反,扩大适用 ...

随机推荐

  1. ES6 教程

    上次分享了es6开发环境的搭建,本次接着分享es6常用的特性. es6常用的语法参考   :    https://blog.csdn.net/itzhongzi/article/details/73 ...

  2. PHP面试 PHP基础知识 三(运算符)

    PHP运算符 PHP的运算符的错误控制符@ PHP支持一个错误运算符:@.当将其放在一个PHP表达式之前,该表达式可能产生的任何错误信息都将会被忽略掉. PHP运算符 运算符的优先级 着重记忆运算符 ...

  3. php5模块pdo、pdo_mysql、mysqli的添加

    一.环境LAMP都是源码安装,PHP安装的时候没有配置pdo_mysql和mysqli,pdo是php5默认带的.PHP5的源码都在,只需要把php5的模块功能扩展就可以了. php源码目录:/usr ...

  4. pefile解析PE格式

    import os,sys import pefile import pydasm import struct #print sys.argv def show_section(pe): print ...

  5. P3224 [HNOI2012]永无乡(平衡树合并)

    题目描述 永无乡包含 nn 座岛,编号从 11 到 nn ,每座岛都有自己的独一无二的重要度,按照重要度可以将这 nn 座岛排名,名次用 11 到 nn 来表示.某些岛之间由巨大的桥连接,通过桥可以从 ...

  6. .net core 根据环境变量区分正式、测试 配置文件

    新建测试.正式环境下所用的 配置信息文件 appsettings.Development.json 文件信息: { "Logging": { "LogLevel" ...

  7. OAuth2.0实例说明

    OAuth2.0 详细实列+Word文档清晰说明 实例下载地址:https://files.cnblogs.com/files/liyanbofly/OAuth2.0%E5%AE%9E%E4%BE%8 ...

  8. Redis缓存数据库简单介绍

    \ 1.什么是redis redis是一种基于内存的高性能键值型数据库(key-value),属于NoSQL,和 Memcached 类似: 从内存读取速度为110000次/s,写入内存速度为8100 ...

  9. jq-demo-拖拽

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  10. 快速求1~n的k!,k的逆元

    1.求1~n的k! 2.求inv(k!) 3.inv((k-1)!)=inv(k!)*k%mod 4.inv(k)=inv(k!)*((k-1)!)%mod 如 https://www.cnblogs ...