前端开发实现JS的原型继承(类继承和原型继承)

前端和后端开发哪个难
前端开发与qt哪个难
前端开发后端开发哪个简单

html 代码

<!DOCTYPE html>
    <head>
        <title>123</title>
    </head>
    <body>
        <script type=”text/javascript”>
            /*通用的原型*/
            var Item = function(name, food) {
                this.name = name
                this.food = food
                /*通用的方法*/
                this.say = function() {
                    console.log(‘我的名字:’ + this.name)
                }
                this.eat = function() {
                    console.log(this.name + ‘喜欢吃’ + this.food)
                }
            }
            Item.prototype.test = function() {
                console.log(‘这里实现了原型继承’)
            }
            /*类继承*/
            var Animal = function(name, food) {
                Item.apply(this, [name, food])
                this.hello = function() {
                    console.log(‘大家好’)
                }
            }
            //animal对应的方法
            Animal.prototype.action = function() {
                console.log(this.name + ‘喜欢’ + this.food)
            }
            var cat = new Animal(‘猫’, ‘鱼’)
            cat.say() //我的名字:猫
            cat.eat() //猫喜欢吃鱼
            cat.action() //猫喜欢鱼
            cat.hello() //大家好
            console.log(typeof cat.test) //undefined
            var Man = function(name, food) {
                Item.call(this, name, food)
                this.tel = function() {
                    console.log(‘我要说’)
                }
            }
            //man对应的方法
            Man.prototype.write = function() {
                console.log(‘我要写’)
            }
            var topthinking = new Man(‘React’, ‘肉’)
            topthinking.say() //我的名字:React
            topthinking.eat() //React喜欢吃肉
            topthinking.tel() //我要说
            topthinking.write() //我要写
            console.log(typeof topthinking.test) //undefined
            //原型继承
            var Woman = function(name, food) {
                this.name = name
                this.food = food
                this.hello = function() {
                    console.log(‘大家好’)
                }
            }
            Woman.prototype = new Item(this.name, this.food)
            var sun = new Woman(‘vue’, ‘蔬菜’)
            sun.say() //我的名字:React
            sun.eat() //vue喜欢吃蔬菜
            sun.hello() //大家好
            console.log(typeof sun.test) //function
            sun.test() //这里实现了原型继承
        </script>
    </body>
</html>
前端开发 哪个好
开发前端和后端哪个好学
前端开发和测试哪个前景好
» 本文来自:前端开发者 » 《前端开发实现JS的原型继承(类继承和原型继承)》
» 本文链接地址:https://www.rokub.com/8201.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!