VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > JavaScript教程 >
  • 关于构造函数和数组原型链上添加构造函数的回顾记录

复制代码
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <h1 style="text-align: center;">内容在控制台</h1>
    </body>
    <script type="text/javascript">
        //创建构造函数
        function Test(name){
            this.name = name;
            this.xbc = '你瞅啥。';
            this.hello = function(){
                console.log('hello,'+this.xbc);
            }
            this.like = function(){
                console.log(this.name+'喜欢瞅你。');
            }
        }
        
        var isMe = new Test('XXX');
        isMe.hello();
        isMe.like();
        
        
        // isMe.constructor === Test.prototype.constructor; // true
        // Test.prototype.constructor === Test; // true
        // Object.getPrototypeOf(isMe) === Test.prototype; // true
        // isMe instanceof Test; // true
        console.log(Test);
        console.log(isMe.constructor);
        console.log(Test.prototype.constructor);
        console.log(Test.prototype);
        console.log(Object.getPrototypeOf(isMe));
        console.log(isMe instanceof Test);
        
        function Cat(param){
            this.name = param.name||'匿名';
            this.old = param.old||'保密';
            this.address = param.address||'未知地区';
            this.introduce = function(){
                console.log('我叫'+this.name+',年龄'+this.old+',来自'+this.address+'');
            };
        }
        
        var xiaobai = new Cat({name:'',address:''});
        var xiaohei = new Cat({name:'',old:'1'});
        var xiaohua = new Cat({name:'',old:'3',address:''});
        var niming  = new Cat({old:'1岁半'});
        xiaobai.introduce();
        xiaohei.introduce();
        xiaohua.introduce();
        niming.introduce();
        
        //查看 数组prototype方法
        console.log(Array.prototype);
        
        //在数组原型链上添加构造函数
        Array.prototype.myFun = function(){
            console.log(this);
            var retArr = [];
            for(var i=0;i<this.length;i++){
                if(this[i]%2 == 1){
                    retArr.push(this[i]);
                }
            }
            return retArr;
        };
        
        Array.prototype.myJoin = function(str){
            var str = str || '';
            var retStr = '';
            for(var i=0;i<this.length;i++){
                if(i == this.length-1)
                retStr += this[i];
                else
                retStr += this[i] + str;
            }
            return retStr;
        };
        
        var arr = [1,2,3,4,5,6,7,8,9];
        console.log(arr.myFun());
        
        console.log(arr.myJoin());
        console.log(arr.myJoin('+'));
    </script>
</html>
复制代码
本文链接:https://www.cnblogs.com/swcffgh/p/14647400.html

相关教程