网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的范文:

 

标题 js创建对象经典模式全面了解
范文
    下面小编就为大家带来一篇js 创建对象 经典模式全面了解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。
    1. 概述
    通过构造函数创建对象, 有时忘记了写new, 这时函数就会返回undefined
    可以创建一个函数createXXX, 在内部封装new。
    function Student(props){
      this.name = props.name || '匿名';
      this.grade = props.grade || 1;  
    }  
    Student.prototype.hello = function(){
      alert('Hello, '+ this.name + '!');
    }
    function createStudent(props){  
      return new Student(props || {});
    }
    注意,如果函数没有显示的写明 return xxx; 则返回undefined。
    example
    利用构造函数定义Cat,并让所有的Cat对象有一个name属性,并共享一个方法say(),返回字符串'Hello, xxx!':
    'use strict';
    function Cat(name) {
      this.name = name;
    }
    Cat.prototype.say = function(){
      return ('Hello, ' + this.name + '!');
    }
    // 测试:
    var kitty = new Cat('Kitty');
    var doraemon = new Cat('哆啦A梦');
    if (kitty && kitty.name === 'Kitty' && kitty.say && typeof kitty.say === 'function' && kitty.say() === 'Hello, Kitty!' && kitty.say === doraemon.say) {
      alert('测试通过!');
    } else {
      alert('测试失败!');
    }
    以上这篇js 创建对象 经典模式全面了解就是小编分享给大家的全部内容了,希望能给大家一个参考
随便看

 

在线学习网范文大全提供好词好句、学习总结、工作总结、演讲稿等写作素材及范文模板,是学习及工作的有利工具。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/20 23:03:39