zoukankan      html  css  js  c++  java
  • Javascript面向对象谈

    一:创建对象:

     //对象封装原始模式
            var Cat = {
                name: '',
                color: '',
                eat: function () { }
            };
    
            function eat() {
                console.log("test");
            }
    
            var cat1 = { name: "binfire", color: "red", eat: eat };

    二:构建类:

     //对象封装
        function Cat(name, color) {
            this.name = name;
            this.color = color;
            this.eat = function () { console.log('eat fish'); };
        }
    
        var cat = new Cat("binfire", "red");
        cat.eat();

    三:Prototype

      //js扩展方法和属性
        function Cat(name, color) {
            this.name = name;
            this.color = color;
        }
        Cat.prototype.type = "mammal";
        Cat.prototype.eat = function () { console.log("fk"); }

    四:Call/Apply继承

     function Animal() {
            this.species = 'animal';
            this.sleep = function () { console.log('I\'m sleep at night'); };
        }
    
        //通过cat对象调用Animal
        /** @class Cat*/
        function Cat(name, color) {
            Animal.apply(this);
            this.name = name;
            this.color = color;
        }
    
        var cat1 = new Cat("binfire", "red");
        cat1.sleep();

    五:原型链原理

        var Person = function () { };
        Person.prototype.Say = function () {
            console.log("person say");
        };
    
        var p = new Person();
        console.log(p.__proto__ == Person.prototype);
        //p没有Say方法,于是去_proto中找,也就是Person.propotype,
        //Person.propotype.Say
        p.Say();

    1.var p={}; 初始化一个对象p
    2.p.__proto__=Person.propotype;
    3.Person.call(p); 构造p,初始化p

    function Animal() {
        this.species = 'animal';
        this.sleep = function () {
            console.log('I\'m sleeping');
        };
    }
    
    function Cat(name, color) {
        this.name = name;
        this.color = color;
    }
    Cat.prototype = new Animal();
    Cat.prototype.eat = function () { console.log("eating") };
    
    var cat = new Cat("binfire", "red");
    cat.sleep();
  • 相关阅读:
    Android编码规范03
    Android编码规范02
    Android编码规范01
    函数返回值类型为枚举类型
    ObjectAnimator属性动画应用demo
    n个元素的入栈顺序有多少种出栈顺序?
    JNI笔记1
    字符串——面试题1:统计一行字符中有多少个单词?
    快速排序算法
    es6之 async await 使用小计
  • 原文地址:https://www.cnblogs.com/binfire/p/2880523.html
Copyright © 2011-2022 走看看