【问题标题】:Is it possible to access the prototype object of function by its function itself是否可以通过函数本身访问函数的原型对象
【发布时间】:2020-10-30 00:10:29
【问题描述】:

例如

//creating constructor function

function Something(){}

//adding name property to Something prototype


Something.prototype.name='javascript';

是否可以从对象本身访问 name 属性?

//喜欢

Something.name

// but here output will be 'undefined'

// 代码

function Fan(){}

Fan.prototype.speed='high';

Fan.speed

//output of (Fan.speed) undefined

【问题讨论】:

标签: javascript function inheritance constructor prototype


【解决方案1】:

不,如果您将其设置为Fan.prototype.speed,则该值位于Fan.prototype.speed 而不是Fan.speed。当您使用Fan 作为对象的构造函数时,即为实例化对象设置一个查找链以查找它在构造函数的prototype 上没有的属性:

const f = new Fan();
console.log(f.speed);  // lookup to Fan.prototype.speed

【讨论】:

    【解决方案2】:

    你可以创建一个对象的实例然后访问它:

    function Something() {}
    Something.prototype.name = 'javascript';
    // create an instance for that
    var x = new Something();
    console.log(x.name);
    
    //Another set of examples, note the prototype on the objects function has no instance so the getName.protytppe.bucket
    const another = {
      secret: "skim",
      name: "cream",
      getName: function() {
        return this.name;
      },
      getSecret: function() {
        return this.secret;
      },
      makeButter: function(n) {
        this.name = n;
        return `We made {this.name} from cream`;
      }
    };
    another.getName.prototype.bucket = "lot-o-milk"
    
    var n = Object.create(another);
    console.log(n.name);
    console.log(n.getName());
    // make cream into butter
    n.name = "butter";
    console.log(n.name);
    console.log(n.getName());
    // turn butter back to cream
    delete n.name;
    console.log(n.name);
    console.log(n.getName());
    n.makeButter('yellow');
    console.log(n.getName());
    console.log(n.getSecret(), n.getName.prototype.bucket);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多