17.寄生构造函数应用,稳妥构造函数
原 javascript读完大概需要2分钟
- 发布时间:2017-07-26 20:32 星期三
- 刘伟波
- 601
- 更新于: 2017-07-26 20:32 星期三
loading...
原 javascript读完大概需要2分钟
<script> //工厂函数+构造函数 不建议使用 function Student(name,age) { var obj=new Object(); obj.name=name; obj.age=age; obj.fun= function () { return this.name+this.age; }; return obj; } var stu=new Student("lisi",23); // console.log(stu.fun());//lisi23 //稳妥构造函数,在一些安全环境中,比如禁止使用this ,new,这里的this是值构造函数不能使用this //这里的New是在外部实例化构造函数时不能使用new function Person(name,age) { var obj=new Object(); obj.fun= function () { return name+age;//直接使用参数的值 }; return obj; } var person=Person("lisi",23);//不能使用new创建对象 // console.log(person.fun());//lisi23 // console.log(Array.prototype.sort);//function sort() { [native code] } // console.log(String.prototype.substring);//function substring() { [native code] } //给js内部的引用类型的原型对象添加方法 String.prototype.myStr= function () {//不建议这样用,避免命名冲突 return this+"是个字符串"; }; var ss="hello"; console.log(ss.myStr());//hello是个字符串 </script>
发表评论: