多种对象定义方式

谁说我不能喝 提交于 2019-11-27 19:33:34
/**
 * 对象定义
 * @authors Your Name (you@example.org)
 * @date    2019-08-18 15:10:38
 * @version $Id$
 */

var print0 = (function() {
    var test = {};
    test.test0 = function() {
        console.log('test0')
        console.log(this)
    }
    return test
})() //{}对象不用new

var print = {
    test: function() {
        return 'fucntion1'
    },
    console: function() {
        console.log('test1')
        console.log(this)
    }
} //{}对象,不用new

var print2 = (function() {
    var print2 = function() {}
    print2.prototype = {
        test2: function() {
            console.log('test2')
            console.log(this)
        }
    }
    return new print2()
})() //函数对象要new

var print3 = (function() {
    var print3 = function() {
        return {
            test3: function() {
                console.log('test3')
                console.log(this)
            }
        }
    }
    return new print3()
})() //函数对象要new

//建议使用,对外api方式
var print4 = (function() {
    function _test41() {
        console.log('test41')
    }
    //_test41不对外暴露
    return {
        test4: function() {
            console.log('test4')
            console.log(this)
            _test41()
        },
        test5: function(r, callback) {
            console.log(callback) //callback回调函数结果在外面执行 function(){}()
        },
        test6: function(r, callback) {
            console.log(typeof callback)
            console.log(callback && (callback)(r)) //callback是回调函数在里面执行 function(){}
        }
    }

})() //{}对象不用new

var print5 = (function() {
    function test5(e, ops) {
        this.e = e;
        this.ops = ops;

    }
    test5.prototype.test5 = function() {
        console.log('test5')
        console.log(this)
        console.log(this.e, this.ops)
    }
    return test5
})() //函数对象在外面new print5 = new print5(1,2)

  

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script type="text/javascript" src="./user.js"></script>
</head>
<body>
    <h1 id="test">测试</h1>
    <script type="text/javascript">
        print0.test0()
        print.console()
        print2.test2()
        print3.test3()
        print4.test4()
        print4.test5('param',function(r){
            return 'callback5'
        }())
        print4.test6('callback6',function(r){
            return r
        })
        
        print5 = new print5(1,2)
        print5.test5()

    </script>
</body>
</html>

 

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!