零js基礎 | 程序設計 | 7 - 函数表达式

name属性获取函数名:IE不支持

    function fn1(name, age) {}
    console.log(fn1.name) //fn1

创建了一个名为f()的命名函数表达式,然后将它赋值给变量factorial

        'use strict'  //兼容严格模式,arguments.callee()不支持严格模式;
        var fa = (function f(num) {
            if (num < 1) {
                return 1
            } else {
                return num * f(num - 1)
            }
        })
        var fac = fa
        fa = null
        fac(8)

闭包是指有权访问另一个函数作用域中的变量的函数

函数调用时,执行环境:1、,作用域链1--全局变量;2、作用域链2--compare()的活动对象argument,v1,v2

function comapre(v1,v2){
    if(v1<v2){return -1}
    else if(v1>v2){return 1}
    else{return 0;}
}
    var result = comapre(5,10) //调用时,创建一个包含 argument,v1,v2的活动对象;
compare()调用---》创建执行环境--》复制函数的[[Scope]]属性--》用来构建起执行环境的作用域链
--》此后,活动对象(arguments与参数)--》推入执行环境作用链前端
在compare()的执行环境--》作用域链包含两个变量对象:本地活动对象(arguments与参数和全局变量对象compare与result

作用域链本质是一个指向变量对象的指针列表,只引用不实际包含;

函数访问一个变量时,会从作用域链接链中搜索具有相应名字的变量,执行完后销毁(即局部变量无法在全局中访问的原因)

闭包

    function createComparisonFunction(propertyName) {
        return function(object1, object2) {
            var value1 = object1[propertyName];
            var value2 = object2[propertyName];
            if (value1 < value2) {
                return -1;
            } else if (value1 > value2) {
                return 1;
            } else {
                return 0;
            }
        };
    }

内部的函数将包含外部函数的活动对象添加到它的作用域链中 【function(o....),的propertyName(活动对象)添加到作用域链中】

var compare = createComparisonFunction("name");
var result = compare({ name: "Nicholas" }, { name: "Greg" });

执行以上代码,return函数返回后,作用域链 == 包含 createComparisonFunction()活动对象和全局变量对象;
createComparisonFunction()函数执行完后,活动对象不会被销毁,执行环境作用域链被销毁,因为return函数仍引用这个活动对象,直到return函数被销毁后,createComparisonFunction()活动对象才被销毁;

//创建函数
var compareNames = createComparisonFunction("name");

//调用函数
var result = compareNames({ name: "Nicholas" }, { name: "Greg" });

//解除对匿名函数的引用(以便释放内存)
compareNames = null;
首先,创建的比较函数被保

createComparisonFunction的执行环境【有两个】,1、createComparisonFunction的活动对象--》arguments,propertyName; 即'name'

2、(作用域链也是链到这两个)--》全局变量对象(createComparison,Function)result

匿名函数的执行环境[有三个]--》0:闭包的活动对象:arguments[{'name':'nic'},{'name':'grey'}]; object1{'name':'nic'};object2:{'name':'grey'}
1、createComparisonFunction执行环境的作用域0:createComparisonFunction的活动对象:arguments,propertyName; 即'name';
2、createComparisonFunction执行环境作用域1:全局变量对象(createComparison,Function)result

所以,即匿名函数的执行环境(作用域链)包含上级函数的作用域链;

JavaScript中的作用域链的机制引出了一个副作用,即闭包只能取得包含函数中任何变量的最后一个值。闭包所保存的是整个变量对象

    function createFunction() {
        var result = [];
        for (var i = 0; i < 10; i++) {
            result[i] = function() {
                return i;
            }
        }
        return result;
    }

    var arr = createFunction()

    for (var i = 0; i < arr.length; i++) {
        console.log(arr[i]()) //10,i变量只取最后一个值
    }

改写一:

    function createFunction() {
        var result = [];
        for (var i = 0; i < 10; i++) {
            result[i] = (function(num) {
                    return num
            })(i)
        }
        return result;
    }

    var arr = createFunction()

    for (var i = 0; i < arr.length; i++) {
        console.log(arr[i])
    }

改写二:

    function createFunction() {
        var result = [];
        for (var i = 0; i < 10; i++) {
            result[i] = function(num) {
                return function(){
                    return num
                };
            }(i)
        }
        return result;
    }
    
    var arr = createFunction()
    for (var i = 0; i < arr.length; i++) {
        console.log(arr[i]())
    }

在重写了前面的createFunctions()函数后,每个函数就会返回各自不同的索引值了。在这个版
本中,我们没有直接把闭包赋值给数组,而是定义了一个匿名函数,并将立即执行该匿名函数的结果赋
给数组。这里的匿名函数有一个参数num,也就是最终的函数要返回的值。在调用每个匿名函数时,我
们传入了变量i。由于函数参数是按值传递的,所以就会将变量i 的当前值复制给参数num。而在这个
匿名函数内部,又创建并返回了一个访问num 的闭包。这样一来,result 数组中的每个函数都有自己
num 变量的一个副本,因此就可以返回各自不同的数值了。

this对象

var name = 'the window'
var Object = {
    name:'my object',
    getNameFun:function(){
        return function(){
            return this.name //这里this-->windows
        }
    }
}
console.log(Object.getNameFun()()) //the window,为什么不是my object?
var name = 'the window'
var Object = {
    name:'my object',
    getNameFun:function(){
        var _this = this; 
        return function(){
            return _this.name
        }
    }
}
console.log(Object.getNameFun()()) //my object

返回第一个例子;

var name = 'the window'
var Object = {
    name:'my object',
    getNameFun:function(){ //活动对象都会自动获取两个特殊的变量:this和arguments
        return function(){   //活动对象都会自动获取两个特殊的变量:this和arguments Object.getNameFun()()调用时,立即返回
            return this.name //这里this-->windows
        }
    }
}
console.log(Object.getNameFun()()) //the window,为什么不是my object?

每个函数在调用时,其活动对象都会自动获取两个特殊的变量:this和arguments。内部函数在搜索这两个变量时,只会搜到其活动对象为止,因此永远不肯能访问到外部函数中的这两个变量。不过,把外部作用域中的this对象保存在一个闭包能够访问的变量里,就可以放闭包访问该对象了。[this相当于两层function(),每一层都有this与arguments,最里层this指向window,上一层指向本身的object]

内存泄漏

    function assHandler(){
        var elem = document.getElementById('someElement')
        elem.onclick = function(){   //匿名函数保存着对assHandler()的活动对象引用,
            console.log(elem.id)//因此就会导致无法减少elem的引用数,只要存在,elem引用数至少也是1,所占内存永远不会被回收,把这里提出去;
        }
    }

改进:

    function assHandler(){
        var elem = document.getElementById('someElement')
        var id = elem.id //保存为副本
        elem.onclick = function(){
            console.log(id)
        }
        elem = null;//即使闭包不直接引用element,包含函数的活动对象中也
仍然会保存一个引用,必要把element 变量设置为null。
    }

块级作用域

    function outputNum(count){
        for(var i=0;i<count;i++){
            console.log(i)
        }
        var i;
        console.log(i) //也是10
    }
    outputNum(10)
     (function() {
                //someCode.
     }();
   var someFn = function(){
        //someCode.
    }
    someFn()

是否可以直接

     function() {

     }() //出错

是因为JavaScript 将function 关键字当作一个函数声明的开始,而函
数声明后面不能跟圆括号。然而,函数表达式的后面可以跟圆括号。要将函数声明转换成函数表达式
只要像下面这样给它加上一对圆括号即可。

无论在什么地方,只要临时需要一些变量,就可以使用私有作用域,例如:

    function outNum(count){
        (function(){
            for(var i=i;i<count;i++){
                console.log(i)
            }
        })()
        console.log(i) //抛出错误
    }
    outNum(5)

所以,可以使用下面方式;

    (function(){
        var now = new Date()
        if(now.getMonth() == 0 && now.getDate() == 1){
            console.log('happy new year')
        }
    })()

把上面这段代码放在全局作用域中,可以用来确定哪一天是1 月1 日;如果到了这一天,就会向用
户显示一条祝贺新年的消息。其中的变量now 现在是匿名函数中的局部变量,而我们不必在全局作用域
中创建它

私有变量

    function MyObject(){
        //私有变量我私有函数
        var privateValue = 10;
        function privateFunction(){
            return false;
        }
        //特权方法
        this.publicMethod = function(){
            privateValue++;
            return privateFunction();
        }
    }

这个模式在构造函数内部定义了所有私有变量和函数。然后,又继续创建了能够访问这些私有成员
的特权方法。能够在构造函数中定义特权方法,是因为特权方法作为闭包有权访问在构造函数中定义的
所有变量和函数

    function Person(name){
        this.getName = function(){  //使用this,避免外部对getName的调用,只能通过Person.getName()
            return name;
        }
        this.setName = function(value){
            name = value;
        }
    }
    var per1 = new Person('nic')
    console.log(per1.getName())
    per1.setName('grey')
    console.log(per1.getName())

以上代码的构造函数中定义了两个特权方法:getName()和setName(),这两个方法都可以在构
造函数外部使用,因为每次调用构造函数都会重新创建这两个方法,构造函数模式的缺点是针对每个实例都会创建同样一组新方法,而使用静态私有变量来实现特权方
法就可以避免这个问题。

//构造函数模式实现私有变量(通过闭包实现)
        function Person(nameStr){
            var name = nameStr;//私有变量
            this.age = 15;//公有变量
            this.getName = function(){
                return name;
            };
            this.setName = function(value){
                name = value;
            };
            this.getInfo = function(){
                console.debug(name + "  " +this.age);
            };
        }
        var p1 = new Person('Lebron');
        var p2 = new Person('Paul');
        p1.getInfo();
        p2.getInfo();
        p1.setName('kobe Bryant');
        p1.getInfo();
        p2.getInfo();

但是这种构造器模式每次调用时都会创建函数对象,耗费资源,函数不可以共享。


静态私有变量

私有作用域中定义私有变量或函数
(function(){
    //私有变量、函数
    var privateValue = 10;
    function privateFun(){
        return false;
    }
    //构造
    MyObject = function(){  //使用函数表达工来构造函数
//因为函数声明只能创建局部函数;并不是我们想要的,出于一样原因,也没有在MyObject前加var
        
    }
    //公有、特权方法
    MyObject.prototype.publicMethod = function(){
        privateValue ++ ;
        return privateFun()
    }
})() 

,就在于私有变量和函数是由实例共享的。由于
特权方法是在原型上定义的,因此所有实例都使用同一个函数。而这个特权方法,作为一个闭包,总是
保存着对包含作用域的引用

(function(){
    var name = '' //静态私有,被所有实例所共享
    Person = function(value){ //默认为全局变量了 ,可以被外部访问  
    name = value;
    }
    Person.prototype.getName = function(){
    return name;
    }
    Person.prototype.setName = function(value){
    name  =value;
    }
})()

    var per1 = new Person('nic')
    console.log(per1.getName())  //nic
    per1.setName('grey')
    console.log(per1.getName())  //grey
    
    var per2 = new Person('mich')
    console.log(per1.getName())  //mich
    console.log(per2.getName())  //mich //被影响了

道格拉斯所说的模块模式(module
pattern)则是为单例创建私有变量和特权方法,所谓单例(singleton),指的就是只有一个实例的对象。
按照惯例,JavaScript 是以对象字面量的方式来创建单例对象的。

先来看看不需要实现对象内属性私有化的对象该如何定义??

        var singleton = {
            name: 'value',
            method: function() {
                //.....
            }
        }

需要对象内属性私有化的定义;

    (function() {
        var singleton = function() {

            //私有变量和私有函数
            var privateValue = 10;

            function privateFun() {
                return false;
            }
            
            //公有、特权方法和属性;
            return { //返回对象的匿名函数
                publicProperty: true,
                publicMethod: function() {
                    privateValue++;
                    return privateFun();
                }
            }
        }

    })()

首先声明了一个私有的components
数组,并向数组中添加了一个BaseComponent 的新实例(在这里不需要关心BaseComponent 的代码,我
们只是用它来展示初始化操作)。而返回对象的getComponentCount()和registerComponent()方法,都
是有权访问数组components 的特权方法。前者只是返回已注册的组件数目,后者用于注册新组件。

function BaseComponent(){
        
    }
    console.debug("=====================");
    var application = function(){//定义的匿名函数立即执行 返回一个匿名的对象字面量
        //私有变量和函数
        var components = new Array();
        //初始化操作
        components.push(new BaseComponent());
        //公共
        return {//返回对象字面量方式定义的对象  以这种方式开放访问接口
           getComponentCount : function(){
               return components.length; 
           },
           registerComponent : function(component){
               if( typeof component == 'object'){
                   components.push(component);
               }
           }
        };
        
    }();
    console.debug(application.getComponentCount());  

改进增强型模块模式;进一步增强的模块模式是指在返回对象志强对其增强功能,这种增强的模块模式适合那些单例必须是某种类型的实例。就像下面这样

    function BaseComponent(){
            }
            function OtherComponent(){
            }
            var application = function(){
                //private variables and functions
                var components = new Array();
                //initialization
                components.push(new BaseComponent());
                //create a local copy of application
                var app = new BaseComponent();
                //public interface
                app.getComponentCount = function(){
                    return components.length;
                };
                app.registerComponent = function(component){
                    if (typeof component == "object"){
                        components.push(component);
                    }
                };
                //return it
                return app;
            }();
            alert(application instanceof BaseComponent);
            application.registerComponent(new OtherComponent());
            alert(application.getComponentCount());  //2

零js基礎 | 程序設計 | 1 - 6 - 基础

5.5.4 函數內部屬性 特殊對象:arguments和 this
arguments下的callee屬性,arguments.calle();指針,指向arguments對象的函數

    function factorial(num) {
        if (num < 1) {
            return 1
        } else {
            return num * factorial(num - 1)
        }
    }

    function factorial2(num) {
        if (num < 1) {
            return 1
        } else {
            return num * arguments.callee(num - 1)
        }
    }

this對象

    window.color = 'red'
    var o = {
        color: 'blue'
    }

    function sayColor() {
        console.log(this.color);
    }
    sayColor() //red
    o.sayColor = sayColor;
    o.sayColor() //blue

函數對象屬性outer(),保存著調用當前函數的函數引用;

    function outer(){
        var i;
        inner()
    }
    function inner(){
        var i=0,b=1,c=3;
        console.log(inner.caller)
    }
    outer()

5.5.5函數屬性和方法

函數的length表示參數的個數

    function sayName(a,b){
        //
    }
    console.log(sayName.length) //2

每個函數都有非繼承方法:apply(),call();,設置函數體內this對象的值;
apply(運行函數的作用域同this,參數組【可以是Array實例,也可以是arguments對象】)
call(運行函數的作用域同this,傳遞的參數一個個列出來)

        function sum(n1, n2) {
            return n1 + n2;
        }

        function callsum1(n1, n2) {
            return sum.apply(this, arguments)
        }

        function callsum2(n1, n2) {
            return sum.apply(this, [n1, n2])
        }
        console.log(callsum1(10, 10))
/////////////////////////////////////////////////////

        function sum(n1, n2) {
            return n1 + n2;
        }

        function callsum(n1, n2) {
            return sum.call(this, n1, n2)
        }
        console.log(callsum(10, 10))

真正的用處:

        window.color = 'red'
        var o = {
            color: 'blue'
        }

        function sayColor() {
            console.log(this.color);
        }
        sayColor(this) // red
        sayColor.call(window) //red
        sayColor.call(o) //blue

bind()方法會創建函數實例,this值會被綁定到傳給bind()函數的值;

        window.color = 'red'
        var o = {
            color: 'blue'
        }

        function sayColor() {
            console.log(this.color)
        }
        var objsaycolor = sayColor.bind(o) //即創建了objsaycolor()函數,其中他的this = o 對象
        objsaycolor(); //blue

5.6基本包裝類型 Boolean/Number/String

        var s1 = 'some txt'
        var s2 = s1.substring(2);

為什麼基本類型調用對象方法

        //創建String實例
        var s1 = new String('some txt')  
        //為實例調用方法
        var s2 = s1.substring(2)
        //銷毀實例
        s1 = null;

方法

var num  = 10;
        console.log(num.toString(2)) //1010;
        console.log(num.toFixed(2)) //10.00
        console.log(num.toExponential(1)) //1.0e+1
        console.log(n.toPrecision(1));
    var n = 99;
    console.log(n.toPrecision(2));  // 1e+2
    console.log(n.toPrecision(3)); //99.0
    console.log(n.toPrecision(4)); //99.00
    表示以多少位显示,范围为 1- 21

不修改字符串本身,返回基本字符串值,
concat()/slice()/substr()/substring()
slice()负与长度相加
substr()、substring()负置为0

var vS = 'fuckword'
console.log(vS.length); //8
console.log(vS.charAt(1)) //u
console.log(vS.charCodeAt(1)) //117
console.log(vS[1]) //u
var rvS = vS.concat('aaaa','bbb')
console.log(rvS) //fuckwordaaaabbb

位置方法:indexOf()/lastIndexOf();

    var strindex = 'jaspfjqijdfjsfnfcjspfqmjfpwpfjmadsljkfmpqiergbrufjnapskdjfmpa';
    var position  = []
    var pos = strindex.indexOf('f');
    while (pos > -1){
        position.push(pos)
        pos = strindex.indexOf('f',pos+1)
    };
    console.log(position);

trim()去空格;
strindex.toLocaleLowerCase()
strindex.toLocaleUpperCase()

match()/search()

    var txt = 'cat bat eat fat'
    var pattern = /.at/

    //与 pattern.exec(txt);
    var matches = txt.match(pattern)  
    console.log(matches.index) //0
    console.log(matches[0])  //at 返回匹配
    console.log(pattern.lastIndex) //0
    var txt = 'cat bat eat fat'
    var pattern = /at/

    var matchs = txt.search(pattern)
    console.log(matchs) //1 at在字符串第一次出现位置1

$n表达匹配第n个子字符串 n : 1-9 nn: 10 -99

var txt = 'cat bat eat fat'
var pattern = /at/
var retxt = txt.replace(/(.at)/g,'word$1')
console.log(retxt)
//wordcat wordbat wordeat wordfat

只有一个匹配:replace(//,function(模式匹配,模式匹配项在字符串中的位置,原始字符串 ){ })
多个匹配:replace(//,function(模式匹配,第一捕获组匹配项,第二捕获组匹配项....,模式匹配项在字符串中的位置,原始字符串 ){ })

function reppacehtml(str) {
    return str.replace(/[<>]/g, function(match, pos, priginalText) {
        switch (match) {
            case "<":
                return '';
            case ">":
                return ''
        }
    })
}
console.log(reppacehtml('<p>heooooooo</p>'))

split(字符串或正则,数组大小)

var colorText = "red,blue,green,yellow";
var colors1 = colorText.split(","); //["red", "blue", "green", "yellow"]
var colors2 = colorText.split(",", 2); //["red", "blue"]
var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""]

localeCompare()方法;

function determineOrder(value) {
    var result = stringValue.localeCompare(value);
    if (result < 0) {
        alert("The string 'yellow' comes before the string '" + value + "'.");
    } else if (result > 0) {
        alert("The string 'yellow' comes after the string '" + value + "'.");
    } else {

        alert("The string 'yellow' is equal to the string '" + value + "'.");
    }
}
determineOrder("brick");
determineOrder("yellow");
determineOrder("zoo");

fromCharCode()方法;String构造函数本身的静态方法,接收一个或多个字符编码,转成字符串;
String.fromCharCode(104,101)

5.7.1 Global对象
encodeURI()整个URI,只有空格会换成20%,其它都原封不动;
encodeURIComponent()主要用于对URI中的某一段;发现任何非标准都转换;

encodeURI('http://baidu.com/google com/')
//"http://baidu.com/google%20com/"
encodeURIComponent('http://baidu.com/google com/')
//"http%3A%2F%2Fbaidu.com%2Fgoogle%20com%2F"

decodeURI()
decodeURIComponent()

eval()方法,解析器;传入的参数当语句来解析;

eval('alert("hi")') = alert("hi")

eval("function sayHi() { alert('hi'); }"); //注意这里有双引号,是一个字符串
sayHi(); //hi

取得global对象方法:

    var global = function(){
        return this;
    }()
    console.log(global)

Math.ceil()/Math.floor()/Math.round()/Math.random()


//介乎于lv与uv之间的数(包括lv/uv)
    function selectFrom(minV,maxV){
        var cV = maxV - minV + 1;
        return Math.floor(Math.random() * cV + minV);
    }
    var num = selectFrom(2,10);
    console.log(num)

EAMAScript 5 定义了描述这些属性特征的各类特性,包括数据属性和访问器属性。

  1. [[Configurable]]:表示是否能通过delete删除
  2. [[Enumerable]]:表示能否用for-in循环返回。
  3. [[writable]]:表示能否修改属性的值。
  4. [[Value]]:包含这个属性的数据值。默认值为undefined。
var person = {};
Object.defineProperty(person, "name", {
writable: false,
value: "Nicholas"
});
alert(person.name); //"Nicholas"
person.name = "Greg";
alert(person.name); //"Nicholas"

已经设置为不能configurable为false,即不能删除,再次设置将抛出错误

var person = {};
Object.defineProperty(person, "name", {
configurable: false,
value: "Nicholas"
});
//抛出错误
Object.defineProperty(person, "name", {
configurable: true,
value: "Nicholas"
});

访问器属性;

访问person.name,实际调用getter()函数,写放时调用setter()函数;
Object.defineProperty( )方法,该方法包含三个参数:属性所在的对象,属性的名字,描述符对象;

    var person = {
        _name: 'elmok', //默认
        _age: 31, //默认
        _tel: 123456 //默认
    }
    Object.defineProperty(person, 'name', {
        get: function() {
            return this._name;
        }
    })
    Object.defineProperty(person, 'age', {
        set: function(newage) {
            this._age = newage;
        }
    })

    console.log(person.name) //elmok
    person.name = 'EE' //尝试修改 
    console.log(person.name) //elmok 不可修改
    console.log(person.age) //不可读属性undefined
    person.age = '26'
    console.log(person._age) //26,可修改,直接读取_age才可看到已改
    console.log(person.tel) //修改
    person.tel = 888888;
    console.log(person.tel) //888888
    
    等价另一种写法
    
    Object.defineProperty(person,{
        name:{
            get:function(){
                return this._name;
            }
        }
    })

//
工厂模式

    function cperson(name,age,job){
        var o = new Object();
        o.name = name;
        o.age = age;
        o.syaName = function(){
            console.log(this.name);
        }
        return o;
    }

构造函数模式

    function Person(name,age,job){
        this.name = name;
        this.age = age;
        this.job = job;
        this.sayName = function(){
            console.log(this.name)
        }
        //this.sayName = new Function('console.log(this.name)')
    }

    console.log(per1.constructor == Person) //true
    console.log(per1 instanceof Object) //true
    console.log(per1 instanceof Person) //true

调用

    //构造调用 
    var per1 = new Person('nicholas',29,'software Engineer')

    //普通函数
    Person('Geay',27,'Doctor')
    window.sayName();

    //另一个对象作用域中调用
    var o = new Object()
    Person.call(o,'Geay',25,'Doctor')
    o.sayName()

问题:

console.log( per1.sayName == per2.sayName ) //false 创建多次了

如果定义在外面

    function Person(name,age){
        this.name = name;
        this.age = age;
        this.sayName = sayName;
    }
    
    function sayName(){
        console.log(this.name)
    }
    
    var per1 = new Person('nicholas',29,'software Engineer')
    var per2 = new Person('grey',28,'Doctor')
    
    console.log( per1.sayName == per2.sayName )  //true;

所以是原型 prototype(原型)属性,指针,指向一个对象
对象的用途:包含可以由特定类型的所有实例共享的属性和方法;
通过创建的那种对象的 ‘ 原型对象 ’

创建新函数--》创建prototype属性 --》 prototype属性指向函数的原型对象

原型对象自动获得constuctor,指向--》prototype所有的函数

Person.prototype 《-- Person.prototype.constructor

Per1.[[prototype]] --> Person.prototype 实例属性仅仅指向Person.prototype
Per2.[[prototype]] --> Person.prototype

确定与实例的[[prototype]]是否有这种关系;isPrototypeOf()

alert(Person.prototype.isPrototypeOf(per1)); //true

ECMAScript 5 Object.getPrototypeOf[per1] == Person.prototype //左边返回对象的原型
alert(Object.getPrototypeOf(person1).name); //"Nicholas"

解析器会问:per1有sayName吗?答:无,则再搜索prototype,答:有;

如果外属性有值,则会覆盖prototype的值;

    function Person() {}
    Person.prototype.name = 'nic'
    Person.prototype.age = 29;
    Person.prototype.sayName = function() {
        console.log(this.name);
    }
    var per1 = new Person()
    var per2 = new Person();

    per1.name = 'grey'
//  delete per1.name  可以删除实例属性,用回原型
    console.log(per1.name)

    alert(person1.hasOwnProperty("name")); //false    

hasOwnProperty()方法,可检测一个属性是存在实例中,还是原型中,来自原型返回false,来自自身属性返回true; 如以上;所以可以确定什么时候访问的是实例属性,什么时候访问的是原型属性

所以 in的方法返回true,而 hasOwnProperty返回 false,则表明在原型

    function hasPrototypeProperty(obj,name){
        return !obj.hasOwnProperty(name) && (name in object)
    }

Object.keys()返回所有可枚举实例属性;--数组;

    function Person() {}
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function() {
        alert(this.name);
    };
    var keys = Object.keys(Person.prototype);
    alert(keys); //"name,age,job,sayName"
    var p1 = new Person();
    p1.name = "Rob";
    p1.age = 31;
    var p1keys = Object.keys(p1);
    alert(p1keys); //"name,age"
    function Person(){}
    Person.prototype = {  //自动创建的 constructor被重写
        name:'nic',
        age:29,
        job:'softw',
        sayName:function(){
            console.log(this.name)
        }
    }
    var per1 = new Person()
    console.log(per1.constructor == Person) //false  constructor属性prototype下的属性,所以访问是实例.的形式,就像访问 .name一样
func.....
Person.prototype = {
    constructor:Person, //重设
}
重设之后会导致constructor的[[Enumerable]]设置为true; 所以

Object.defineProperty(Person.prototype,'constructor',{
    enumerable:false,
    value:Person
})

可以先创建实例,再创建原型,但如果重点整个原型,以{}的形式写,则情况不一样,会切断构造函数与最初原型的联系,记住:实例的指针仅指向原型,而不是指向构造函数;

情况一:

function Person(){}  //1、定义构造
var f = new Person() //2、定义实例
    Person.prototype.sayHi = function(){ //3、定义原型
        console.log('hi')
    }
f.sayHi()  //原型在实例之后定义也可访问到;即任何位置;

情况二:

function Person(){}  //1、定义构造
var f = new Person() //2、定义实例
Person.prototype = { //3、重写原型
    constructor:Person,
    name:'nic',
    age:29,
    job:'soft',
    sayName:function(){
        console.log(this.name)
    }
}
f.sayName()    //error,f因为引用的是最初的原型

//而Person()引用的是重写的原型

常用的方法都是定义在其构造函数的原型上

console.log(typeof Array.prototype.sort) //function

原型的问题:

function Person(){}    
Person.prototype = {
  constructor:Person,
  friends:['shelby','court'],
  sayName:function(){
      console.log(this.name)
  }
}
    var per1 = new Person()
    var per2 = new Person()
    per1.friends.push('van')
    console.log(per2.friends) //["shelby", "court", "van"] 只修改1,2也被影响了;

使用组合,可变写在构造里,不可改即共享部分写在原型里

function Person(name,age){
    this.name = name;
    this.age = age;
    this.list = ['111','2222']
}
Person.prototype = {
    constructor:Person,
    sayName : function (){
        console.log(this.name)
    }
}    
var per1= new Person('elmo1',29)
var per2= new Person('elmo2',30)

per1.name = 'elmo8'
per1.list.push('333')

console.log(per1.name) //elmo8
console.log(per2.name) //elmo2
console.log(per1.list) //["111", "2222", "333"]
console.log(per2.list) //["111", "2222"]

动态原型 (只有sayName()不存在时,才加到原型)

    function Person(name,age,job){
        this.name = name;
        this.age = age;
        this.job = job;
        if(typeof this.syaName != 'function'){
            Person.prototype.sayName = function(){
                console.log(this.name)
            }
        }
    }
    var f = new Person('nic',29,'sf')
    f.sayName()

寄生式,即未原型时

function Person(name,age,job){
    var o = new Object();
    o.name = name;
    o.age = age;
    o.job = job;
    o.syaName = function (){
        console.log(this.name)
    }
    return o;
}
    var f = new Person('nic',29,'sf')
    f.sayName(); //nic

寄生式
返回的对象或构造函数之间没有任何关系,因此不能依赖 instanceof来确定

    function SpecitalArray(){
        var values = new Array();
        values.push.apply(values,arguments);
        values.toPipedString = function(){
            return this.join('|')
        }
        return values;
    }
    var colors = new SpecitalArray('red','blue','green')
    console.log(colors.toPipedString());
    console.log(colors instanceof SpecitalArray)

稳妥构造函数模式

无公共属性,不引用this new

    function Person(name,age,job){
        va o = new Object()
        o.sayName = function(){
            console.log(name)
        }
        return o
    }
    var f = Person('nic',29,'sf')
    f.sayName()
    function SuperType(){
        this.property = true;
    }
    SuperType.prototype.getSuperValue = function (){
        return this.property;
    }
    function SubType(){
        this.subproperty = false;
    }
    SubType.prototype = new SuperType()
    SubType.prototype.getSubvalue = function(){
        return this.subproperty;
    }
    var instance = new SubType(); //重写,所以instance.constructor-->SuperType
    instance.getSuperValue();
    
    //搜索实例--》搜索SubType.prototype--》搜索SuperType.prototype-->最后一步才找到方法;
    
    console.log(instance instanceof Object)
    console.log(instance instanceof SuperType)
    console.log(instance instanceof SubType)

继承

function SuperType(){
this.property = true;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subproperty = false;
}
//继承了SuperType
SubType.prototype = new SuperType();
//添加新方法
SubType.prototype.getSubValue = function (){
return this.subproperty;
};
//重写超类型中的方法
SubType.prototype.getSuperValue = function (){
return false;
};
var instance = new SubType();
alert(instance.getSuperValue()); //false

原型链的问题;

    function SuperType() {
        this.color = ['red', 'blue', 'green']
    }

    function SubType() {

    }
    SubType.prototype = new SuperType()
    var in1 = new SubType()
    in1.color.push('black')
    console.log(in1.color) //["red", "blue", "green", "black"]

    var in2 = new SubType()
    console.log(in2.color) //["red", "blue", "green", "black"] 被影响到

借用构造函数

function SuperType(name){
    this.name = name
}
function SubType(){
    SuperType.call(this,'nic') //可以传递参数
    this.age = 29;
}    
    var in1 = new SubType()
    console.log(in1.name) //nic
    console.log(in1.age);//29

组合继承--伪经典继承;

    function SuperType(name) {
        this.name = name;
        this.colors = ['red', 'blue', 'green']
    }
    SuperType.prototype.sayName = function() {
        console.log(this.name)
    }

    function SubType(name, age) {
        SuperType.call(this, name)
        this.age = age;
    }

    SubType.prototype = new SuperType()
    SubType.prototype.constructor = SubType;
    SubType.prototype.sayAge = function() {
        console.log(this.age)
    }
    var in1 = new SubType('nic', 29)
    in1.colors.push('black')
    console.log(in1.colors) //["red", "blue", "green", "black"]
    in1.sayName() //nic
    in1.sayAge() //29

    var in2 = new SubType('grey', 27)
    console.log(in2.colors); //["red", "blue", "green"]
    in2.sayName() //grey
    in2.sayAge() //27

原型式继承

    function object(o) {
        function F() {}
        F.prototype = o;
        return new F(); //内部复制一次再返回,相当于浅复制 ;
    }
    var person = {
        name: 'nic',
        friends: ['shll', 'count', 'van']
    }
    var per1 = object(person)
    per1.name = 'grey'
    per1.friends.push('rob')
    var per2 = object(person)
    per2.name = 'linda'
    per2.friends.push('barbie')
    console.log(person.friends) //["shll", "count", "van", "rob", "barbie"]
Object.create(新对象原型的对象,新对像定义额外属性的对象)
    var person = {
        name: 'nic',
        friends: ['shll', 'count', 'van']
    }
    
    var per1 = Object.create(person,{
        name:{
            value:'grey'
        }
    })
    console.log(per1.name)

寄生式继承

    function createAnother(original){
        var clone = Object(original); //创建一个新对象
        clone.sayHi = function(){ //某种方式增强这个对象
            console.log('hi')
        }
        return clone; //最后再返回增强后的对象
    }

最有效有方式:寄生组合式继承

组合继承的问题

    function SuperType(name){
        this.name = name;
        this.colors = ['red','blue','green']
    }
    SuperType.prototype.sayName = function(){
        console.log(this.name)
    }

    function SubType(name,age){

        SuperType.call(this,name); 
        //第二次调用 SuperType,这一次又在新对象上创建实例属性 name,colors,于是这两个属性就屏蔽了第一次调用时原型中的同名属性;

        this.age = age;
    }

    SubType.prototype  = new SuperType(); 
    //第一次调用 SuperType Sub.prototype会得到两个属性 name colors; 

    SubType.prototype.constructor = SubType;
    SubType.prototype.sayAge = function(){
        console.log(this.age)
    }

所谓寄生组合式继承,即通过借用构造函数来继承属性,通过原型链的混成形式来继承方法

inheritPrototype(子类型构造函数,超类型构造函数),用于原型复制;
    function inheritPrototype(subType,superType){
        var prototype = object(superType.prototype) //创建对象
        prototype.constructor = subType;        //增强对象
        subType.prototype = prototype;          //指定对象
    }
1、创建superType.prototype函数副本
2、为创建的副本添加constructor属性
3、将副本赋值给subType的原型 
    function inheritPrototype(subType,superType){
        var prototype = Object(subType.prototype) //创建对象
        prototype.constructor = subType;        //增强对象
        subType.prototype = prototype;          //指定对象
    }
    
    function SuperType(name){
        this.name = name;
        this.colors = ['red','blue','green']
    }
    SuperType.prototype.sayName  = function(){
        console.log(this.sayName)
    }
    function SubType(name,age){
        SuperType.call(this,name)
        this.age = age;
    }
    inheritPrototype(SubType,SuperType);  //改写
    SubType.prototype.sayAge = function(){
        console.log(this.age)
    };
    
    var per1 = new SubType('nnn',30)
    console.log(per1.colors) //['red','blue','green']
    console.log(per1.sayAge()) //30

这个例子的高效率体现在它只调用了一次SuperType 构造函数,并且因此避免了在SubType.
prototype 上面创建不必要的、多余的属性。与此同时,原型链还能保持不变;因此,还能够正常使用
instanceof 和isPrototypeOf()

ECMAScript 支持面向对象(OO)编程,但不使用类或者接口。对象可以在代码执行过程中创建和
增强,因此具有动态性而非严格定义的实体。在没有类的情况下,可以采用下列模式创建对象。
 工厂模式,使用简单的函数创建对象,为对象添加属性和方法,然后返回对象。这个模式后来
被构造函数模式所取代。
 构造函数模式,可以创建自定义引用类型,可以像创建内置对象实例一样使用new 操作符。不
过,构造函数模式也有缺点,即它的每个成员都无法得到复用,包括函数。由于函数可以不局
限于任何对象(即与对象具有松散耦合的特点),因此没有理由不在多个对象间共享函数。
 原型模式,使用构造函数的prototype 属性来指定那些应该共享的属性和方法。组合使用构造
函数模式和原型模式时,使用构造函数定义实例属性,而使用原型定义共享的属性和方法。
JavaScript 主要通过原型链实现继承。原型链的构建是通过将一个类型的实例赋值给另一个构造函
数的原型实现的。这样,子类型就能够访问超类型的所有属性和方法,这一点与基于类的继承很相似。
原型链的问题是对象实例共享所有继承的属性和方法,因此不适宜单独使用。解决这个问题的技术是借
用构造函数,即在子类型构造函数的内部调用超类型构造函数。这样就可以做到每个实例都具有自己的
属性,同时还能保证只使用构造函数模式来定义类型。使用最多的继承模式是组合继承,这种模式使用
原型链继承共享的属性和方法,而通过借用构造函数继承实例属性。
此外,还存在下列可供选择的继承模式。
 原型式继承,可以在不必预先定义构造函数的情况下实现继承,其本质是执行对给定对象的浅
复制。而复制得到的副本还可以得到进一步改造。
 寄生式继承,与原型式继承非常相似,也是基于某个对象或某些信息创建一个对象,然后增强
对象,最后返回对象。为了解决组合继承模式由于多次调用超类型构造函数而导致的低效率问
题,可以将这个模式与组合继承一起使用。
 寄生组合式继承,集寄生式继承和组合继承的优点与一身,是实现基于类型继承的最有效方式。