JavaScript经典案例(二)

169 阅读1分钟

13.GO、prototype

function Foo() {
    getName = function () {
        console.log(1);
    }
    return this;
}
Foo.getName = function () {
    console.log(2)
}
Foo.prototype.getName = function () {
    console.log(3);
}
var getName = function () {
    console.log(4);
}
function getName() {
    console.log(5)
}
Foo.getName();              //2
getName();                   //4  GO 执行时赋值为function[4]输出4
Foo().getName();            //1   Foo执行,getName没有声明,所以是全局的,GO里getName被重新赋值
getName();                  //1 getName变为function[1]
new Foo.getName();         //2  Foo没执行,.的优先级高于new ,所以是new 2 依然是2
new Foo().getName();     // 3 (new Foo()).getName,寻找构造函数里的getName,本身没有,从原型找
new new Foo().getName()  // 3  new 3

分析:GO={  Foo:function

                       getName: undefined->function【5】 ->function【4】->function【1】

                    }

/** * 判断回文 * */
function checkPlalindrome(str){
    return str === str.split('').reverse().join('');
}
/** * 数组去重 * */
Array.prototype.unique = function () {
    var temp = {},
        newArr = [],
        len = this.length;
    for(var i = 0; i < len; i++){
        if(!temp.hasOwnProperty(this[i])){
  //!temp[this[i]] 用hasOwnProperty  是为了去掉数组中重复的0
            temp[this[i]] = this[i];
            newArr.push(this[i])
        }
    }
    return newArr
}
String.prototype.unique = function () {
    var temp = {},
        newStr = '';
    for(var i=0;i<this.length;i++){
        if(!temp.hasOwnProperty(this[i])){
            temp[this[i]] = this[i];
            newStr += this[i]
        }
    }
    return newStr;
}
var str = '124eeerrrll'
str.unique()
function unique(arr){
    let hasObj = {},
        data = [];
    for (let item of arr){
        if(!hasObj[item]){
            hasObj[item] = true;
            data.push(item)
        }
    }
    return data;
}
// console.log(unique([1,1,2,3,45,8,0,0,6,5,1]))
/** * 字符串中第一个不重复的字符 */
function test(str) {
    var temp = {};
    for (var i = 0; i<str.length;i++){
        if(temp.hasOwnProperty(str[i])){
            temp[str[i]]++
        }else {
            temp[str[i]] = 1
        }
    }
    for(var key in temp){
        if(temp[key] === 1){
            return key;
        }
    }
}

判断数据具体类型(原始值、引用值、包装类)

function type(target){
    var ret = typeof(target);
    var template = {
        "[object Array]" : "array",
        "[object Object]" : "object",
        "[object Number]" : "number-object",
        "[object Boolean]" : "boolean-object",
        "[object String]" : "string-object"
    }
    if(target === null){
        return "null";
    }else if(ret == 'object'){
        var str = Object.prototype.toString.call(target);
        return template[str];
    }else
        return ret;
}