JavaScript prototype delegation in function

This question already has an answer here:

  • How does JavaScript .prototype work? 21 answers

  • What you have is a constructor function that has m in its prototype.

    var func = function (){};
    func.prototype = {m:9};
    
    console.log( func.prototype.m ); // That logs 9
    

    The prototype is assigned not to the function itself but to instances created by this function:

    var f = new func();
    
    console.log( f.m ); // That also logs 9
    

    This is where your m is.

    For this to also log 9

    func.m
    

    you'd have to have m in Function.prototype because the prototype of func is Function

    Function.prototype.m = 9;
    
    console.log( func.m ); // Logs 9
    

    By doing func.prototype = {m:9}; , you are setting the 'prototype' property of your func variable to {m:9} .

    When you call, func.m , you try to access the 'm' property of your func variable, which you never set before.

    Instead, you previously set the 'm' property of the object func.prototype .

    If you want to set the property 'm' from your variable func , simply do func.m = 9;

    链接地址: http://www.djcxy.com/p/30086.html

    上一篇: 什么JavaScript的prototype.constructor的?

    下一篇: JavaScript原型委托功能