博客列表 >Javascript_二_变量类型和计算

Javascript_二_变量类型和计算

开源
开源原创
2019年02月01日 13:50:58521浏览

变量类型 

值类型

var a = 100;

var b = a;

a = 200;

console.log(b); //100

引用类型(对象、数组、函数)

var a = {age:20};

var b = a;

a.age = 21;

console.log(b.age); //21

typeof运算符

typeof undefined;

typeof 'abc';

typeof 123;

typeof true;

typeof {};

typeof [];

typeof null;

typeof console.log;

变量计算

类型转换

字符串拼接

var a = 100 + '10';

==运算符

100 == '100'; //true

0 = ''; //true

null = undefined; //true

if语句

if(a = true) {}

if(b = 100) {}

if(c = '') {}

逻辑运算符

10 && 0

'' || 'abc'

!window.abc

!!a

问题

typeof

=== ==

if(obj.a == null) {}

相当于obj.a === null || obj.a === undefined简写

内置函数

对象、数组、函数。布尔,数字,文字,日期,正则,错误

存储方式 值 和 引用

JSON 对象 API


构造

function Foo(name,age) {

this.name = name;

this.age = age;

//return this;

}

var f = new Foo('zhangsan',20);

//var f = new Foo('lisi',21);


var o = {} -> var o = new Object();

var a = [] -> var a = new Array();

function Foo -> var Foo = new Function();

instanceof

原型

var o = {}; o.a = 100;

var a = []; a.a = 100;

function f() {}; f.a = 100;

console.log(o.__proto__);

console.log(a.__proto__);

console.log(f.__proto__);

console.log(f.prototype);

console.log(o.__proto__ === Object.prototype);


function Foo(name,age) {

this.name = name;

}

Foo.prototype.alerName = function() {

alert(this.name);

}

var f = new Foo('zhangsan')

f.printName = function() {

console.log(this.name);

}

f.printName();

f.alertName();

hasOwnProperty判断是否属于自身属性

f.tostring();

原型链

instanceof判断是否属于某类型


原型链继承

function Animal() {

this.eat = funcation() {

console.log('Animal eat');

}

}

function Dog() {

this.bark = funcation() {

console.log('Dog bark');

}

}

Dog.prototype = new Animal();

var hashipi = new Dog();


一个贴近实际应用的原型链继承的列子

function Elem(id) {

  this.elem = document.getElementById(id);

}

Elem.prototype.html = function (val) {

  let elem = this.elem;

  if(val){

    elem.innerHTML = val;

    return this ;//作链式操作

  }else{

    return elem.innerHTML;

  }

};

Elem.prototype.on = function (type,fn) {

  let elem = this.elem;

   elem.addEventListener(type,fn);

   return this;

};

//使用

let div1 = new Elem('wrap');

div1.html();

div1.html('<p>this is from prototype</p>').on('click',function () {

  alert('clicked')

}).html('<p>second time change</p>');


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议