js笔记

Posted 追恋KG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js笔记相关的知识,希望对你有一定的参考价值。

引用

对象通过引用来传递,它们永远不会被拷贝。

var a = {
    name: ‘a‘
}
var b = a
b.name = ‘bconsole.log(a.name)     // b

这里牵扯出 javascript 深拷贝和浅拷贝的问题
上例是浅拷贝

深拷贝见下:

var deepCopy= function(source) { 
    var result={};
    for (var key in source) {
      result[key] = typeof source[key]===’object’? deepCoyp(source[key]): source[key];
   } 
   return result; 
}

此时 var b = deepCopy(a) 得到的 b 就和 a 没有引用关系,即修改 b 不会影响 a 了

创建一个对象时,可以选择某个对象作为它的原型:

var o = {o1:1,o2:function(){alert(1)}}
function F(){}
F.prototype = o
var f = new F()


一个函数被保存为对象的一个属性时,即为一个方法当一个方法被调用时,this 被绑定到该对象
var dog = {
    name : ‘xxx‘ ,
    leg:{
        sum : 4 ,
        move:function(){
            console.log(this) ; //Object,是leg对象,而不是dog对象,下面证明了
            alert(this.name) ; //underfined
            alert(this.sum) ; //4
        }
    }
}
dog.leg.move();

call:
var dog = {
    leg : 4 ,
    color:‘yellow‘
}
var color = ‘red‘ ;
function t(){
    alert(this.color) ;
}
t(); // red , 因为指向this在函数中调用指向window
t.call(dog); //yellow , 把t()的作用域指向了dog


try catch 能捕捉throw抛出的异常

function add(a,b){
    if(typeof a!==‘number‘ || typeof b!==‘number‘){
        throw {
            name: ‘TypeError‘,
            message: ‘add needs numbers‘
        }
}
    return a + b;
};
function a(){
    try{
        add(‘1‘,3);
    }catch(e){
        console.log(e.name)
        console.log(e.message)
    }
}
a();

 

给类型增加方法:

Number.prototype.integer = function(){
    return Math[this < 0 ? ‘ceiling: ‘floor‘](this) //this指向实例
}

var num = 10/3
console.log(num.integer())  ;   // 3


var o = (function(){
    var val = 0;
    return {
        addVal: function(){
            val += 1
        },
        getVal: function(){
            console.log(val)
        }
    }
})()//val外部不能访问,闭包

判断是否是数组或对象:
var is_array = function(value){
    return value && 
        typeof value === ‘object&&
        typeof value.length === ‘number&&
        typeof value.splice === ‘function&&
        !(value.propertyIsEnumerable(‘length‘))
}
var toString = Object.prototype.toString
function isObject(obj) {
  return toString.call(obj) === "[object Object]"
}
function isString(obj) {
  return toString.call(obj) === "[object String]"
}
function isArray(obj) {
  return toString.call(obj) === "[object Array]"
}
function isFunction(obj) {
  return toString.call(obj) === "[object Function]"
}
 



 

以上是关于js笔记的主要内容,如果未能解决你的问题,请参考以下文章

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

VSCode自定义代码片段——JS中的面向对象编程

VSCode自定义代码片段9——JS中的面向对象编程

js代码片段: utils/lcoalStorage/cookie

JS代码片段:一个日期离现在多久了

js常用代码片段(更新中)