js-面向對象學習

  • 檢測對象是否擁有某一屬性,能夠用in操做符判斷;若是in判斷一個屬性存在,這個屬性有多是繼承的。要判斷一個屬性是不是自身擁有的,而不是繼承獲得的,能夠用hasOwnProperty()方法。

JavaScript不區分類和實例的概念,而是經過原型(prototype)來實現面向對象編程。java

var stu = {
    name : 'name',
    age : 23
}
var xiaoming = {
    name : 'xiaoming'
}
xiaoming.__proto__ = stu;//把xiaoming的原型指向了stu,看起來像是繼承了;

在編寫JavaScript代碼時,不要直接用obj.proto__去改變一個對象的原型,而且,低版本的IE也沒法使用__proto。Object.create()方法能夠傳入一個原型對象,並建立一個基於該原型的新對象,可是新對象什麼屬性都沒有。編程

//原型對象;
var stu = {
    name : 'name',
    age : 23
}
function createStu(name){
    //基於stu原型建立一個新對象
    var obj = Object.create(stu);
    //初始化新對象;
    s.name = name;
    return obj;
}

javaScript對每一個建立的對象都會設置一個原型,指向它的原型對象。 當咱們用obj.xxx訪問一個對象的屬性時,JavaScript引擎先在當前對象上查找該屬性,若是沒有找到,就到其原型對象上找,若是尚未找到,就一直上溯到Object.prototype對象,最後,若是尚未找到,就只能返回undefined。函數

var arr = [1, 3, 5]
//原型鏈
arr ----> Array.prototype---->Object.prototype ----> null

function foo() {
    return 0;
}
//原型鏈
foo ----> Function.prototype ----> Object.prototype ----> null

對象的構造函數this

function Students(name) {
            this.name = name;
            this.hello = function (){
                console.log('create student, name:' + this.name);
            }
}    
var stu = new Students('xiaoli');
//原型鏈
stu ----> Students ----> Object.prototype ----> null

用new xxx()建立的對象還從原型上得到了一個constructor屬性,它指向函數Student自己:prototype

調用構造函數千萬不要忘記寫new。爲了區分普通函數和構造函數,按照約定,構造函數首字母應當大寫,而普通函數首字母應當小寫.code

定義對象和繼承:對象

class Student {
            constructor(name) {
                this.name = name;
            }

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

class PrimaryStudent extends Student {
            constructor(name, grade) {
                super(name);
                this.grade = grade;
            }

            myGrade(){
                alert('I am at grade ' + this.grade);
            }
        }
相關文章
相關標籤/搜索