Android开发WEB前端程序开发手机移动程序开发

面向Android的快速学习JavaScript笔记(基础篇 下

2017-02-11  本文已影响0人  Rayhaha

本篇是快速学习JavaScript笔记的最后一篇,很多地方总结的不好,所以说的会比较详细。
前面两篇的快速学习笔记:
面向Android的快速学习JavaScript笔记(基础篇 上)
面向Android的快速学习JavaScript笔记(基础篇 中)
如有理解错误的地方,希望大家可以踊跃指出,我立即修改
最后继续附上廖雪峰大神的JavaScript详细教程


目录:


面向对象编程

基本概述

var Student = {
    name: 'Robot',
    height: 1.2,
    run: function () {
        console.log(this.name + ' is running...');
    }
};

var xiaoming = {
    name: '小明'
};

xiaoming.__proto__ = Student;
//小明的原型指向Student,所以现在小明也可以使用run()
//也就相当与Java的继承

!注意:
不要直接使用  obj.__proto__ 去指向原型,应使用下面这种方法
// 原型对象:
var Student = {
    name: 'Robot',
    height: 1.2,
    run: function () {
        console.log(this.name + ' is running...');
    }
};

function createStudent(name) {
    // 基于Student原型创建一个新对象:
    var s = Object.create(Student);
    // 初始化新对象:
    s.name = name;
    return s;
}

var xiaoming = createStudent('小明');
xiaoming.run(); // 小明 is running...
xiaoming.__proto__ === Student; // true



创建对象

var arr = [1, 2, 3];
其原型链是:
arr ----> Array.prototype ----> Object.prototype ----> null
//原型链越长,访问对象属性的时间就越长,所以原型链不应过长
function Student(name) {
    this.name = name;
    this.hello = function () {
        alert('Hello, ' + this.name + '!');
    }
}
//使用new来创建对象
var xiaoming = new Student('小明');
xiaoming.name; // '小明'
xiaoming.hello(); // Hello, 小明!
不使用new就返回undefined
使用new就会默认返回this,this指向这个对象本身


使用new 创建的对象还从原型上获得了一个constructor属性,它指向函数Student本身:

xiaoming.constructor === Student.prototype.constructor; // true
Student.prototype.constructor === Student; // true

Object.getPrototypeOf(xiaoming) === Student.prototype; // true

xiaoming instanceof Student; // true

xiaoming.name; // '小明'
xiaohong.name; // '小红'
xiaoming.hello; // function: Student.hello()
xiaohong.hello; // function: Student.hello()
xiaoming.hello === xiaohong.hello; // false

这里不同对象的hello函数是不一样的,不过他们对于我们使用来说应该是一样的才行,所以
function Student(name) {
    this.name = name;
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};
可以让Student的原型去创造hello函数
这样后面的student对象使用的hello就一样了
对于忘记使用new的话,this指向的就是window对象,也就是在全局创建了一个name属性
比较合理的创建对象的构造应该是这样的:
function Student(props) {
    this.name = props.name || '匿名'; // 默认值为'匿名'
    this.grade = props.grade || 1; // 默认值为1
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};

function createStudent(props) {
    return new Student(props || {})
}

原型继承

// PrimaryStudent构造函数:
function PrimaryStudent(props) {
    Student.call(this, props);
    this.grade = props.grade || 1;
}

// 空函数F:
function F() {
}

// 把F的原型指向Student.prototype:
F.prototype = Student.prototype;

// 把PrimaryStudent的原型指向一个新的F对象,F对象的原型正好指向Student.prototype:
PrimaryStudent.prototype = new F();

// 把PrimaryStudent原型的构造函数修复为PrimaryStudent:
PrimaryStudent.prototype.constructor = PrimaryStudent;

// 继续在PrimaryStudent原型(就是new F()对象)上定义方法:
PrimaryStudent.prototype.getGrade = function () {
    return this.grade;
};

// 创建xiaoming:
var xiaoming = new PrimaryStudent({
    name: '小明',
    grade: 2
});
xiaoming.name; // '小明'
xiaoming.grade; // 2

// 验证原型:
xiaoming.__proto__ === PrimaryStudent.prototype; // true
xiaoming.__proto__.__proto__ === Student.prototype; // true

// 验证继承关系:
xiaoming instanceof PrimaryStudent; // true
xiaoming instanceof Student; // true
//实现对象之间的继承函数
function inherits(Child, Parent) {
    var F = function () {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}

class继承

//使用class创建对象
class Student {
    constructor(name) {
        this.name = name;
    }

    hello() {
        alert('Hello, ' + this.name + '!');
    }
}

//继承的使用
class PrimaryStudent extends Student {
    constructor(name, grade) {
        super(name); // 记得用super调用父类的构造方法!
        this.grade = grade;
    }

    myGrade() {
        alert('I am at grade ' + this.grade);
    }
}


浏览器

概述

主要浏览器:

需要注意:某某安全浏览器,某某旋风浏览器,它们只是做了一个壳,其核心调用的是IE

对于编写JavaScript的时候,就要充分考虑到浏览器的差异,尽量让同一份JavaScript代码能运行在不同的浏览器中


浏览器对象

    var width;
if (getIEVersion(navigator.userAgent) < 9) {
    width = window.innerWidth || document.body.clientWidth;
}
location.href; //http://www.example.com:8080/path/index.html?a=1&b=2#TOP
location.protocol; // 'http'
location.host; // 'www.example.com'
location.port; // '8080'
location.pathname; // '/path/index.html'
location.search; // '?a=1&b=2'
location.hash; // 'TOP'

`location.assgin('/di');` //加载新页面
`location.reload();` //重新加载当前页面

操作DOM

概述:

// 返回ID为'test'的节点:
var test = document.getElementById('test');

// 先定位ID为'test-table'的节点,再返回其内部所有tr节点:
var trs = document.getElementById('test-table').getElementsByTagName('tr');

// 先定位ID为'test-div'的节点,再返回其内部所有class包含red的节点:
var reds = document.getElementById('test-div').getElementsByClassName('red');

// 获取节点test下的所有直属子节点:
var cs = test.children;

// 获取节点test下第一个、最后一个子节点:
var first = test.firstElementChild;
var last = test.lastElementChild;

//版本<IE8是不支持下面功能的
// 通过querySelector获取ID为q1的节点:
var q1 = document.querySelector('#q1');

// 通过querySelectorAll获取q1节点内的符合条件的所有节点:
var ps = q1.querySelectorAll('div.highlighted > p');

更新DOM

// 获取<p id="p-id">...</p>
var p = document.getElementById('p-id');
// 设置文本为abc:
p.innerHTML = 'ABC'; // <p id="p-id">ABC</p>
// 设置HTML:
p.innerHTML = 'ABC <span style="color:red">RED</span> XYZ';
// <p>...</p>的内部结构已修改
// 获取<p id="p-id">...</p>
var p = document.getElementById('p-id');
// 设置文本:
p.innerText = '<script>alert("Hi")</script>';
// HTML被自动编码,无法设置一个<script>节点:
// <p id="p-id"><script>alert("Hi")</script></p>

版本<IE9是不支持textContent
// 获取<p id="p-id">...</p>
var p = document.getElementById('p-id');
// 设置CSS:
p.style.color = '#ff0000';
p.style.fontSize = '20px';
p.style.paddingTop = '2em';

插入DOM

<!-- HTML结构 -->
<p id="js">JavaScript</p>
<div id="list">
    <p id="java">Java</p>
    <p id="python">Python</p>
    <p id="scheme">Scheme</p>
</div>

var
    js = document.getElementById('js'),//获取节点
    list = document.getElementById('list');
list.appendChild(js);//在尾部添加节点

var 
    python=document.getElementById('python');//获取python节点
    haskell = document.createElement('p'); //创建节点
haskell.id = 'haskell'; //设置节点属性
haskell.innerText = 'Haskell';
list.innerBefore(haskell,python);

<!-- HTML结构 -->
<div id="list">
    <p id="java">Java</p>
    <p id="haskell">Haskell</p>
    <p id="python">Python</p>
    <p id="scheme">Scheme</p>
    <p id="js">JavaScript</p>
</div>

删除DOM


操作表单

// <label><input type="radio" name="weekday" id="monday" value="1"> Monday</label>
// <label><input type="radio" name="weekday" id="tuesday" value="2"> Tuesday</label>
var mon = document.getElementById('monday');
var tue = document.getElementById('tuesday');
mon.value; // '1'
tue.value; // '2'
//对于选框要使用checked来获取
mon.checked; // true或者false
tue.checked; // true或者false
!-- HTML -->
<form id="test-form" onsubmit="return checkForm()">
    <input type="text" name="test">
    <button type="submit">Submit_Two</button>
    <button type="button" onclick="doSubmitForm()">Submit_One</button>
</form>

//第一种方式
<script>
function doSubmitForm() {
    var form = document.getElementById('test-form');
    // 可以在此修改form的input...
    // 提交form:
    form.submit();
}
</script>

//第二种港式
<script>
function checkForm() {
    var form = document.getElementById('test-form');
    // 可以在此修改form的input...
    // 继续下一步:
    return true;
}
</script>

操作文件

var f = document.getElementById('test-file-upload');
var filename = f.value; // 'C:\fakepath\test.png'
var
    fileInput = document.getElementById('test-image-file'),
    info = document.getElementById('test-file-info'),
    preview = document.getElementById('test-image-preview');
// 监听change事件:
fileInput.addEventListener('change', function () {
    // 清除背景图片:
    preview.style.backgroundImage = '';
    // 检查文件是否选择:
    if (!fileInput.value) {
        info.innerHTML = '没有选择文件';
        return;
    }
    // 获取File引用:
    var file = fileInput.files[0];
    // 获取File信息:
    info.innerHTML = '文件: ' + file.name + '<br>' +
                     '大小: ' + file.size + '<br>' +
                     '修改: ' + file.lastModifiedDate;
    if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        alert('不是有效的图片文件!');
        return;
    }
    // 读取文件:
    var reader = new FileReader();
    reader.onload = function(e) {
        var
            data = e.target.result; // 'data:image/jpeg;base64,/9j/4AAQSk...(base64编码)...'            
        preview.style.backgroundImage = 'url(' + data + ')';
    };
    // 以DataURL的形式读取文件:
    reader.readAsDataURL(file);
});
reader.readAsDataURL(file);
reader.onload = function(e) {
    // 当文件读取完成后,自动调用此函数:
};

AJAX

AJAX: Asynchronous JavaScript and XML :用JavaScript执行异步网络请求
这里直接跳到网页去看吧:
走你: AJAX


Promise

用于封装异步操作,以便根据异步操作是否成功来进行后续的操作。
走你:Promise


Canvas

坐标
canvas在HTML中的定义
<canvas id="test-stock" width="300" height="200">
    <p>Current Price: 25.51</p>//浏览器对H5的支持不一致,所以最好加上说明性代码,这一句就是,如果浏览器支持,就会忽略这一句代码
</canvas>

var ctx = canvas.getContext('2d');//获取2Dcanvas

var gl = canvas.getContext("webgl");//获取3D canvas

ctx.clearRect(0, 0, 200, 200); // 擦除(0,0)位置大小为200x200的矩形,擦除的意思是把该区域变为透明
ctx.fillStyle = '#dddddd'; // 设置颜色
ctx.fillRect(10, 10, 130, 130); // 把(10,10)位置大小为130x130的矩形涂色
// 利用Path绘制复杂路径:
var path=new Path2D();
path.arc(75, 75, 50, 0, Math.PI*2, true);
path.moveTo(110,75);
ctx.strokeStyle = '#0000ff'; //颜色
ctx.stroke(path); //将路径画在canvas上

//绘制文本
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.shadowBlur = 2;
ctx.shadowColor = '#666666';
ctx.font = '24px Arial';
ctx.fillStyle = '#333333';
ctx.fillText('带阴影的文字', 20, 40);

最后:
对于JavaScript的基础学习就到这里了,这个系列只是简单的让大家对JS有一个快速的认知和掌握,具体在开发中还是要慢慢琢磨,希望对在做安卓开发又想拓展一下前端知识的你有一点点帮助。
至于前端后面的一些框架的学习使用的笔记,近期是没有写的打算了。
PS:
下一步会把数据结构和算法的知识捋一遍,并记录在我的博客中
如果对这方面内功知识有兴趣的,可以关注一下哈。

上一篇下一篇

猜你喜欢

热点阅读