Object.create

//一、Object.create
//Object.create 方法是JavaScript中用于创建对象的一个方法 , 接收两个参数,第一个表示要继承的对象,第二个参数(可选)表示也是一个对象,用于对新创建的对象进行初始化 。
//1.初始化对象
        var Obj = {
            name: 'mini',
            age: 3,
            show: function () {
                console.log(this.name + " is " + this.age);
            }
        };

        var MyObj = Object.create(Obj, {
            like: {
                value: "fish", // 初始化赋值
                writable: true, // 是否是可改写的
                configurable: true, // 是否能够删除,是否能够被修改
                enumerable: true //是否可以用for in 进行枚举
            },
            hate: {
                configurable: true,
                get: function () {
                    console.log(111);
                    return "mouse"
                }, // 获取对象hate属性时触发的方法
                set: function (value) { // 设置对象hate属性时触发的方法 
                    console.log(value, 2222);
                    return value;
                }
            }
        });

        // console.log(MyObj.name); // mini
        // console.log(MyObj.like); // fish
        // MyObj.like = "peanut"; 
        // console.log(MyObj.like); // peanut
        // MyObj.hate; // 111    触发get方法
        // MyObj.hate = 'dog'; // dog,2222   触发set方法


//2.继承
var A = function () { };
A.prototype.sayName=function () {
    console.log('a');
}

// B的实例继承了A的属性
var B = function () { };
B.prototype = Object.create(A.prototype);
var b = new B();
b.sayName();  // a

// 重新改写B的prototype
B.prototype= {
    sayName:function () {
        console.log("b");
    }
}

//  改写后,B的实例属性发生了变化
var b1 = new B();
b1.sayName();  //b

//  A的实例维持原来的属性,没有被改写。达到了我们想要的继承效果
var a1 = new A();
a1.sayName(); //a

//兼容处理
if(typeof Object.create != "function") {
   //圣杯
   Object.create=function (o) {
      function F() {}
      F.prototype=o;
      return new F();
   }
}


//二、对象构建几种方式
/*1、字面量方式*/
var a = {};
console.log(a.__proto__);  //Object {}
console.log(a.__proto__ === a.constructor.prototype); //true

/*2、构造器方式*/
var A = function(){};
var a = new A();
console.log(a.__proto__); //A {}
console.log(a.__proto__ === a.constructor.prototype); //true

/*3、Object.create()方式*/
var a1 = {a:1}
var a2 = Object.create(a1);
console.log(a2.__proto__); //Object {a: 1}

// 三、原型链的原理: 原型链就是通过对象的 __proto__ 属性递归到 null 的过程
var A = function(){};
var a = new A();
console.log(a.__proto__); //A {}(即构造器function A 的原型对象)
console.log(a.__proto__.__proto__); //Object {}(即构造器function Object 的原型对象)
console.log(a.__proto__.__proto__.__proto__); //null

猜你喜欢

转载自www.cnblogs.com/justSmile2/p/9956858.html