zoukankan      html  css  js  c++  java
  • 一个不成熟的编程员,写写 js 的面向对象

    其实感觉本人 js 并未入门,甚至说也是个不合格的编程员,什么面向对象都不会,一直都往 Object 里面填方法,假装很对象的样子。

    但学习嘛,这道坎还是得多试几下的,说不定就跨过去了呢。

    个人喜欢用的两种构造对象的方法是这样的:

    function createPerson(name, age) {
        var o = new Object();
        o.name = name;
        o.age = age;
        o.getName = function () {
            return this.name;
        }
        return o; //使用return返回生成的对象实例
    }
    var person = createPerson('Jack', 19);
    

    据说这种叫工厂模式,但对我而言也就那样啦,和直接 var o = {name:"",age:"",fn:function(){}}; 不一样的是能创多个 o 了,不错不错

    function Person(name, age){
        this.name = name;
        this.age = age;
        this.getName = function () {
            return this.name;
        }
    }
    var person1 = new Person('Jack', 19);
    

    据说这种叫构造函数模式,但对我而言也就那样啦,就加了 new 感觉挺爽的,真的有种产生新对象的感觉了,虽然 this 是个相当磨人又可爱的小妖精。

    function Person(name, age){
      this.name = name;
      this.age = age;
    }
    Person.prototype.getName = function(){
        return this.name;
    }
    var person1 = new Person("Jack", 19);
    

    据说这种叫原型模式,但对我而言也就那样啦,好像重写和扩展挺方便的样子。

    后来好像还有混合型的,但我先不管了,再来玩玩面向对象里的继承吧,觉得是个用起来很爽的东西:

    function Animal() {
        this.spacies = "Animal";
    }
    
    // 继承 方法一:
    function fn1() {
        function Cat(name, color) {
            Animal.apply(this, arguments);
            this.name = name;
            this.color = color;
        }
        var cat = new Cat("小花1", "red");
        console.log(cat.spacies );
    }
    // 继承 方法二:
    function fn2() {
        function Cat(name, color) {
            this.name = name;
            this.color = color;
        }
        Cat.prototype = new Animal();
        Cat.prototype.constructor = Cat;
        var cat = new Cat("小花2", "red");
        console.log(cat.spacies);
    }
    

    没错,我就是这么 low 逼,面向对象都还不会,你来打我呀,做人嘛,最重要的是开心咯,我下面给你吃?

  • 相关阅读:
    LeetCode Subsets II
    LeetCode Rotate Image
    LeetCode Palidrome Number
    LeetCode Generate Parentheses
    LeetCode Maximum Subarray
    LeetCode Set Matrix Zeroes
    LeetCode Remove Nth Node From End of List
    Linux Loop设备 使用
    Linux 文件系统大小调整
    LeetCode N-Queens II
  • 原文地址:https://www.cnblogs.com/foreverZ/p/js-object-oriented.html
Copyright © 2011-2022 走看看