Discuss / JavaScript / Niube Class

Niube Class

Topic source

Junes_99994

#1 Created at ... [Delete] [Delete and Lock User]

function Niube(props = {}) {

                /*

                the steps taken when "new x()" is called are essentially:

                Create a new object

                Assign prototype property of x to object's internal [[Prototype]] property

                just like this.__proto__ = x.prototype

                Call x as normal, passing it the new object as this

                If the call to x returned an object, return it, otherwise return the new object

            */

                const generation = props.generation || 1;

                if (!this.__Constructed) {

                    this.name = this.constructor.name

                    this.generation = generation

                    Object.defineProperty ?

                        Object.defineProperty(this, '__Constructed', {

                            value: true,

                            writeable: false,

                            enumerable: false

                        }) :

                        this.__Constructed = true;

                } else console.log(this.constructor.name + " fail to construct ");

            }

            Niube.prototype = {

                print: function() {

                    console.log(this.generation + " liaoxuefeng " + this.name + this.ex);

                },

                ex: "!",

                constructor: Niube // constructor: Object 是默认情况

            };

            function HenNiube(props) {

                Niube.call(this, props);

                this.generation += 1;

            }

            function wrap(proto) {

                function F() {} //constructor

                F.prototype = proto; //get ref addr of proto

                return new F(); // return new object setting proto as Prototype

            }

            // HenNiube.prototype = wrap(Niube.prototype) || Object.create(Niube.prototype);

            // HenNiube.prototype = {

            //     ...Niube.prototype,

            //     constructor: HenNiube

            // }

            // HenNiube.prototype = new Niube();

            /*由于现代 JavaScript 引擎优化属性访问所带来的特性的关系,

            更改对象的 [[Prototype]]在各个浏览器和 JavaScript 引擎上都是一个很慢的操作*/

            // Object.setPrototypeOf(HenNiube.prototype, Niube.prototype);

            HenNiube.prototype.__proto__ = Niube.prototype

            HenNiube.prototype.constructor = HenNiube;

            const h1 = new Niube();

            const h2 = new HenNiube();

            const h22 = new HenNiube();

            HenNiube.prototype.ex = "!!"

            h22.ex = "!!!"

            h1.print()

            h2.print()

            h22.print()

            log(HenNiube.prototype)

            log(Niube.prototype)


  • 1

Reply