您好,欢迎访问一九零五行业门户网

JS克隆,属性,数组,对象,函数实例分析

本文实例讲述了js克隆,属性,数组,对象,函数。分享给大家供大家参考,具体如下:
<script type="text/javascript"> /* 克隆原型得到对象 */ function clone(object) { function f() {} f.prototype = object; return new f; } var person = { name: 'default name', getname: function() { return this.name; } }; var reader = clone(person); console.log(reader.getname()); // this will output 'default name'. reader.name = 'john smith'; console.log(reader.getname()); // this will now output 'john smith'. /* author prototype object. */ var author = clone(person); author.books = []; // 书数组 author.getbooks = function() { return this.books; } var author = []; author[0] = clone(author); author[0].name = 'dustin diaz'; author[0].books = ['javascript design patterns']; author[1] = clone(author); author[1].name = 'ross harmes'; author[1].books = ['javascript design patterns','php','mysql']; console.log(author[0].getname()); console.log(author[0].getbooks()); console.log(author[1].getname()); console.log(author[1].getbooks()); </script>
这里的console.log很有意思,比alert有意思,alert不能获取全部数据,需要一个个弹出。
js的数组定义也很有意思。
进一步升级
<script type="text/javascript"> /* 克隆原型得到对象 */ function clone(object) { function f() {} f.prototype = object; return new f; } var person = { name: 'default name', getname: function() { return this.name; } }; var author = clone(person); author.books = []; // 书数组 author.getbooks = function() { return this.books; } var authorclone = clone(author); console.log(authorclone.name); // string 'default name'. authorclone.name = 'new name'; // 重新赋值 console.log(authorclone.name); // now linked to the primative authorclone.name, which // is the string 'new name'. console.log(author.getname()); // 没有改变,任然是 'default name' console.log(author.getbooks()); // 空的 authorclone.books.push('new book'); // author被改了 authorclone.books.push('new new book'); // author被改了 console.log(author.getbooks()); // array 'new book' console.log(authorclone.getbooks()); // array 'new book' authorclone.books = []; // 定义了属于自己的books数组 authorclone.books.push('new book2'); // we are now modifying that new array. authorclone.books.push('new book3'); authorclone.books.push('new book4'); console.log(authorclone.getbooks()); console.log(author.getbooks()); var compoundobject = { string1: 'default value', childobject: { bool: true, num: 10 }, getchild: function() { // 返回对象object return this.childobject; } } var compoundobjectclone = clone(compoundobject); compoundobjectclone.childobject.num = 5; // 不好的方式 compoundobjectclone.childobject = { // 好一点的方式 bool: true, num: 5 }; console.log(compoundobjectclone.getchild()); </script>
其它类似信息

推荐信息