Javascript 上帝说,我的对象想要默认值

找了下貌似这一篇没写,于是乎坑出了可能是一个月前的代码mark。

我们来看以下两段

        window.Option = {};

        Option.defaultProps = function(obj, defaults) {
            function isObject(obj) {
                return Object.prototype.toString.call(obj) === '[object Object]';
            }

            if (!isObject(obj)) {
                return defaults;
            }

            for (var key in defaults) {
                if (!defaults.hasOwnProperty(key)) {
                    continue;
                }

                var objValues = obj[key];
                var defaultValue = defaults[key];

                if (isObject(objValues)) {
                    obj[key] = Option.defaultProps(objValues, defaultValue);
                } else if (objValues === undefined) {
                    obj[key] = defaultValue;
                }
            }
            return obj;
        };

        function People() {};

        People.defaults = {
            name: 'Hi',
            job: 'Student',
            age: 19,
            friends: ['No One']
        };

        people1 = Option.defaultProps({
            name: 'Sky',
            age: 20
        }, People.defaults);

        people1.prototype = People.prototype;

        People.prototype = {
            constructor: People
        };

        People.prototype.sayName = function() {
            console.log(this.name);
        };

        People.prototype.sayName.call(people1);

        console.log(Object.getPrototypeOf(people1) == People.prototype);


        people2 = new People();

        console.log(people2.prototype);

这一种类型似乎略繁琐,但他确实实现了默认值,当然,相比之下实在是不够优秀,有各种问题,包括constructor之类的。这里我们之所以不直接定义函数,而是先用对象,再里面再加一个方法,是因为javascript没有命名空间(namespace)的概念,万一重名了=A=~

        function Person(name, age, job, friends) {
            this.name = name || "hi";
            this.age = age || 19;
            this.job = job || "Student";
            this.friends = friends || "No one";
        }

相比之下,我们来看这样一段= =唔,很明显他更加常用。

如果您觉得文章不错,可以通过赞助支持我

标签: 知识, 代码段

添加新评论