zoukankan      html  css  js  c++  java
  • 原型链

    function Foo() {
    this.value = 42;
    }
    Foo.prototype = {
    method: function() {}
    };

    function Bar() {}

    // 设置Bar的prototype属性为Foo的实例对象
    Bar.prototype = new Foo();

    Bar.prototype.foo = 'Hello World';

    // 修正Bar.prototype.constructor为Bar本身
    Bar.prototype.constructor = Bar;


    var test = new Bar() // 创建Bar的一个新实例

    // 原型链
    test [Bar的实例]

    Bar.prototype [Foo的实例]
    { foo: 'Hello World' }
    Foo.prototype
    {method: ...};
    Object.prototype
    {toString: ... /* etc. */};

      上面的例子中,test 对象从 Bar.prototype 和 Foo.prototype 继承下来;因此,它能访问 Foo 的原型方法 method。同时,它也能够访问那个定义在原型上的 Foo 实例属性 value。需要注意的是 new Bar() 不会创造出一个新的 Foo 实例,而是重复使用它原型上的那个实例;因此,所有的 Bar 实例都会共享相同的 value 属性。

      我们可以赋值任何类型的对象到原型上,但是不能赋值原子类型的值,比如如下代码是无效的:

    function Foo() {}
    Foo.prototype = 1; // 无效

      JavaScript 不会保护 hasOwnProperty 被非法占用,因此如果一个对象碰巧存在这个属性,就需要使用外部的 hasOwnProperty 函数来获取正确的结果。

    var foo = {
    hasOwnProperty: function() {
    return false;
    },
    bar: 'Here be dragons'
    };

    foo.hasOwnProperty('bar'); // 总是返回 false

    // 使用{}对象的 hasOwnProperty,并将其上下为设置为foo
    {}.hasOwnProperty.call(foo, 'bar'); // true
      当检查对象上某个属性是否存在时,hasOwnProperty 是唯一可用的方法。同时在使用 for in loop 遍历对象时,推荐总是使用 hasOwnProperty 方法,这将会避免原型对象扩展带来的干扰


  • 相关阅读:
    DDPG
    Actor Critic
    Policy Gradients
    DQN
    Sarsa
    粘滞键
    Codeforces Round #236 (Div. 2) E. Strictly Positive Matrix 强连通
    hdu 1853 Cyclic Tour KM
    hdu 3435 A new Graph Game KM
    hdu 3488 Tour KM
  • 原文地址:https://www.cnblogs.com/happyPawpaw/p/2479302.html
Copyright © 2011-2022 走看看