一起學習下 插件的開發,原生的。 看了這文章
JavaScript插件開發從入門到精通系列---原生JavaScript插件開發
附上
讀完小結:
看了下,比較小白的方式就是把一些代碼,放到一個單獨的js文件中, (剛開始就是這么玩的,還覺得挺美)
直接暴露在全局作用域。
-----------------
然后還有用一個建一個
var person1 = {
name: "peter",
age: 18,
sayHello: function() {
alert("hello! I am " + this.name);
}
};
person1.sayHello();
-----------------
然后還有一點工廠模式 , return 返回
function createPerson(name, age) {
var o = new Object();
o.name = name;
o.age = age;
o.sayHello = function() {
alert("hello! I am " + this.name);
};
return o;
}
var person1 = createPerson("peter", 18);
person1.sayHello();
---------------
然后還有一點 構造函數模式 ,使用時new一下
var Person = function(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
alert("hello! I am " + this.name);
}
};
var person1 = new Person("peter", 18);
person1.sayHello();
var person2 = new Person("william", 19);
-------------
上面這些,寫過點代碼的,基本都會經常使用。
作者文章的大干貨 ,精彩來了
原型模式
var MathUtil = function(version, programmer) { this.name = name; this.programmer = programmer; }; MathUtil.prototye = { // 將構造函數置為MathUtil,這里一定要將constructor重新設置回MathUtil,不然會指向Object的構造函數 constructor: MathUtil, // 加法 add: function(aaa, bbb) { var result= aaa + bbb; alert("result == " + result); }, // 減法 reduce: function(aaa, bbb) { var result= aaa - bbb; alert("result == " + result); }, // 乘法 multiply: function(aaa, bbb) { var result= aaa * bbb; alert("result == " + result); }, // 除法 divide: function(aaa, bbb) { var result = aaa / bbb; alert("result == " + result); } };
// 引用mathUtil.js文件后使用方式: var m1 = new MathUtil("william",["william"]); m1.programmer.push("william2"); var m2 = new MathUtil("peter",["peter"]); m1.programmer.push("peter2");
更多的回原文看下,多看幾遍。