javascript笔记---貌似大叔

时间:2023-03-09 09:19:02
javascript笔记---貌似大叔

1、原型式继承和类式继承的区别

在基于类的面向对象方式中,对象(object)依靠类(class)来产生。而在基于原型的面向对象方式中,对象(object)则是依靠 构造器(constructor)利用 原型(prototype)构造出来的。

a:原型继承

var father = function(){};

father.prototype = {

add:function(){
console.log('a的原型方法:加法')
}, delete:function(){ console.log('a的原型方法:减法') } } var son = new father(); smSon.add()

b:类式继承

function Super(){

this.colors=["red","blue"];
console.log(this.color) } function Sub(){

Super.call(this); } var cb = new Sub(); console.log(cb.colors)
console.log(cb)

2、单例模式

function Construct(){
// 确保只有单例
if( Construct.unique !== undefined ){
return Construct.unique;
}
// 其他代码
this.name = "NYF";
this.age="24";
Construct.unique = this;
} var t1 = new Construct() ;
var t2 = new Construct() ; console.log(t1===t2)

3、数组去重

方式一:把第一个元素先放入结果中再来遍历结果数据和原数组
Array.prorotype.unique = function(){
var result = [this[0]]; var repeat = false; for(var i=0;i<this.length; i++){ for(var j=0;j<result.length;j++){ if(result[j]==this[i]){ repeat = true; break; } } if(!repeat){ result.push(this[i]) } } }  方式二:把相同的内容放到一个对象中作为一个对象的属性,并赋值为1(真值),当存在时就取假值!1,这个做法很聪明,想法很独特
Array.prototype.unique2 = function(){

var result = [];
var json = {};

for(var i=0; i<this.length; i++){ if(!json[this[i]]){ result.push(this[i])
json[this[i]] = 1;
} 
}
}